在父組件http請求中更新子組件後,我似乎無法看到子組件中已更改的@Input。如何在子組件中調用具有http請求的父項功能後更新父組件的變量
這是一個例子:
家長
import { ChildComp } from './child.component';
@Component({
template: <child [counter]="a" [updateCounter]="updateCounter"></child>,
directives: [ChildComp]
})
export class ParentComponent {
public a = 1;
public CallBack:Function;
constructor(private _http:Http) {}
public ngOnInit() {
this.CallBack = this.updateCounter.bind(this);
}
public updateCounter() {
this._http.get('/newcounter/').subscribe(
data => {
// update counter
this.a = JSON.parse(data['_body']);
},
error => {},
() => console.log('updated counter')
);
}
}
兒童
@Component({
selector: 'child',
template: `
<button class="btn btn-default" (click)="updateCounter()"></button>
<p>counter: {{ counter }}</p>
`,
inputs: ["counter", "updateCounter"]
})
export class ChildComponent {
public counter;
public updateCounter:Function;
constructor() {}
}
所以,這一點,如果沒有http請求的工作。但是一旦我有請求,子視圖將不會更新計數器。
任何想法?我錯過了什麼?
一個黑客,我現在是setTimeout
子組件上更新呼叫後,計數器500毫秒到updateCounter
那是我第一次嘗試,但沒有奏效。它就像後面的一個狀態,它在每次按下按鈕後顯示前一個計數器 – Brian
將updateCounter方法作爲參考傳遞給您的ChildComponent以觸發更新。根據文檔,我建議你使用EventEmitter而不是你的解決方案。在官方文檔中查找示例:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#inputs-outputs – Matt