當我的應用程序組件中的列表屬性發生改變時,AJAX調用已經返回,但我的視圖沒有相應更新。Angular 2沒有更新HTTP上的視圖獲取調用返回
以下是部分:
import {Component} from '@angular/core';
import {ValuesService} from "./services/ValuesService";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ValuesService]
})
export class AppComponent {
values: string[];
constructor(private valuesService: ValuesService) {
this.values = ['1', '2'];
}
onClick() {
this.valuesService.getValues().subscribe(this.onValues)
}
onValues(values: string[]) {
for (let value of values) {
console.log(value);
}
this.values = values // this should change the view
}
}
觀點:
<button (click)="onClick()">Hit Me</button>
<div *ngFor="let value of values">
<h3>{{value}}</h3>
</div>
當我按一下按鈕,我看到控制檯:
received value1,value2,value3
app.component.ts:27 value1
app.component.ts:27 value2
app.component.ts:27 value3
然而,鑑於沒有按不會改變。
什麼可能導致此問題?這裏是我的依賴關係的package.json:
"dependencies": {
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"core-js": "^2.4.1",
"rxjs": "^5.1.0",
"zone.js": "^0.8.4"
},
編輯:
的修復方法是:
this.valuesService.getValues().subscribe(this.onValues)
到
this.valuesService.getValues().subscribe(values => this.onValues(values))
看起來像this.values =值line.onValues中的內容不是評估應用程序的「this」,而是評估函數本身。這與範圍界定有關。
你能變成一個plunker? – DeborahK
@DeborahK嗯讓我看看我是否可以做到 –