2016-07-08 39 views
0

在父組件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

回答

1

修改你的父組件的這樣的updateCounter功能:

public updateCounter() { 
    let that = this; 
    this._http.get('/newcounter/').subscribe(
     data => { 
      // update counter 
      that.a = JSON.parse(data['_body']); 
     }, 
     error => {}, 
     () => console.log('updated counter') 
    ); 

} 

使用this該承諾不再引用你的課程。所以你需要在另一個變量中保留對this的引用,並使用該變量。

+0

那是我第一次嘗試,但沒有奏效。它就像後面的一個狀態,它在每次按下按鈕後顯示前一個計數器 – Brian

+0

將updateCounter方法作爲參考傳遞給您的ChildComponent以觸發更新。根據文檔,我建議你使用EventEmitter而不是你的解決方案。在官方文檔中查找示例:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#inputs-outputs – Matt

0

您的updateCounter函數是從子組件調用的,其上下文this指的是ChildComponent的實例。

嘗試以下操作:

export class ParentComponent { 
    ... 
    public ngOnInit() { 
    this.updateCounter = this.updateCounter.bind(this); 
    } 
相關問題