簡體   English   中英

使用Observables傳播Angular 2中的更改

[英]Using Observables to propagate changes in Angular 2

我有兩個部分,父母和孩子:

// Parent Directive
@Component({
   selector: 'parent-directive',
   template: `
    <button (click)="nextVal($event)"></button>
    <button (click)="prevVal($event)"></button>
    <child-directive [content]="myValue"></child-directive>`,
   directives: [ChildDirective]
})
export class ParentDirective {
    public myValue : string;

    constructor() {this.myValue = "Hello";}

    nextVal() {this.myValue = "Next";}

    prevVal() {this.myValue = "Prev";}
}

這是子指令:

// Child directive
type ObservableContent = Observable<string>;

@Component({
    selector: 'child-directive',
    template: `<div></div>`
})
export class ChildDirective {
    @Input() content : ObservableContent;
    subscription : Subscription;

    constructor() {
        // I instantiate the content property as an observer. I want to see if it logs anything.
        this.content = new Observable<string>(ob => {console.log('constructor', ob)});

        // I'm trying to get the propagated values here.
        this.subscription = this.content.subscribe(value => { console.log('value', value);});
    }
}

讓我分解一下我想在這里做什么。 我有一個嵌套在父組件中的子組件。 父級有兩個按鈕, nextprev ,單擊它們可更改綁定到父級范圍的屬性。

子級具有另一個屬性,即與父級的myValue范圍屬性綁定的content 當我在父myValue中更新myValue時,我希望更改子級的content屬性。 但是,當我嘗試訂閱該值時,永遠不會調用訂閱偵聽器。 我究竟做錯了什么?

如我所見, content是字符串,而不是Observable。 因此,您無需在此使用.subscribe ,因為它會引發錯誤。

在您的子組件中, this.content將始終為您提供最新的價值。 只需使用changeDetection: ChangeDetectionStrategy.OnPush 這樣可以確保只有在更改了輸入屬性之一的情況下,angular才會更新組件。

要獲取組件中最新的content值,請使用ngOnChanges提供的ngOnChanges生命周期方法。

// Child directive
type ObservableContent = Observable<string>;

@Component({
    selector: 'child-directive',
    template: `<div>{{content}}</div>`,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildDirective {
    @Input() content : ObservableContent;

    ngOnChanges(changes) {
     console.log('new content' + changes.content.currentValue);
     console.log('old content' + changes.content.previousValue);
  }
}

由於Angular的更改檢測,模板中的內容將始終反映更新后的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM