我尝试使用Observable
和ChangeDetectionStrategy
来通知其他组件有关更改的信息。不幸的是,Observable对象addItemStream
未定义。这有什么不对?
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input } from '@angular/core'
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'bp-header',
templateUrl: 'app/header.component.html',
directives: [ROUTER_DIRECTIVES],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeaderComponent {
@Input() addItemStream: Observable<any>;
public isActive: number;
public language: string = "en";
constructor(private cd: ChangeDetectorRef) {}
ngOnInit() {
this.isActive = 1;
}
ngAfterViewInit() {
this.addItemStream.subscribe(() => {
this.setLanguage; // application state changed
this.cd.markForCheck();
})
}
public setLanguage = (language: string) => {
if (this.language === language) { return }
else { this.language = language };
}
public setActive(active: number) {
if (this.isActive === active) return;
this.isActive = active;
}
}
答案 0 :(得分:2)
您正在订阅Observable
中的ngOnInit
。
由于它是Input
,Observable
(以及所有其他Inputs
)此时将为undefined
。
尝试在ngAfterViewInit
订阅它。
或者,提供服务。这使你的生活(和分享Observable
)变得更加容易。
答案 1 :(得分:0)
您订阅它的位置并不重要。我通常在构造函数中执行此操作。但是,当组件初始化时,流是未定义的,所以只需在构造函数中初始化它:
constructor(private cd: ChangeDetectorRef) {
this.addItemStream = new Observable<any>();
}