您可能希望实现该OnChanges
接口并实现该ngOnChanges()
方法.只要其中一个组件输入或输出绑定值发生更改,就会调用此方法.另请参见https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
飞镖代码示例
@Input() bool fixed; @override void ngOnChanges(Mapchanges) { print(changes); }
你可能会发现这个回答是委托:Angular2中的EventEmitter或Observable很有用(为我工作).
基本上你可以使用a BehaviorSubject
,它允许你为你感兴趣的属性设置初始值,然后在注入服务的任何地方订阅对该属性的更改.
例如,如果我正确理解你,就像这样:
export class SomeService {
private fixed = new BehaviorSubject(true); // true is your initial value
fixed$ = this.fixed.asObservable();
private set isFixed(value: boolean) {
this.fixed.next(value);
console.log('isFixed changed', value);
}
private get isFixed():boolean {
return this.fixed.getValue()
}
constructor(router: Router, location: Location) {
this.router = router;
this.location = location;
}
}
然后在对fixed
值感兴趣的类(例如Component)中:
export class ObservingComponent {
isFixed: boolean;
subscription: Subscription;
constructor(private someService: SomeService) {}
ngOnInit() {
this.subscription = this.someService.fixed$
.subscribe(fixed => this.isFixed = fixed)
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
更新价值:
export class Navigation {
constructor(private someService: SomeService) {}
selectedNavItem(item: number) {
this.someService.isFixed(true);
}
}