我有以下组件类从服务接收observable。我希望我的组件在销毁时取消订阅。这是代码正在运行并且视图得到更新(视图根据具有* ngIf的状态值呈现不同的内容):
@Component({
templateUrl: 'my-widget.component.html',
selector: 'my-widget'
})
export class MyWidgetComponent implements OnInit, OnDestroy {
// Enum type variable to keep state
state: MyWidgetStateType;
// This is needed to be able to use the enum type in the template
private myWidgetStateType = MyWidgetStateType;
// Keep a reference to the observable to unsubscribe from it
private sub: Subscriber<any>;
constructor(public myWidgetService: MyWidgetService) {
}
ngOnInit(): void {
this.sub = Subscriber.create((state: MyWidgetStateType) => {
console.log('Widget state: ' + MyWidgetStateType[state]);
this.state = state;
});
this.myWidgetService.getState().subscribe(this.sub);
}
ngOnDestroy(): void {
// Unsubscribe here
this.sub.unsubscribe();
}
}
状态类型是具有3种状态的枚举:
export enum MyWidgetStateType {
Enabled,
Dormant,
Locked
};
视图my-widget.component.html
:
<h2>My Widget</h2>
<div *ngIf="state === myWidgetStateType.Enabled">
<p>Enabled</p>
</div>
<div *ngIf="state === myWidgetStateType.Dormant">
<p>Dormant</p>
</div>
<div *ngIf="state === myWidgetStateType.Locked">
<p>Locked</p>
</div>
但是,如果我尝试将订阅者中的调用解压缩到私有函数,则console.log方法可以工作,但视图不会根据状态呈现任何内容(<h2>
标题是渲染但没有<div>
元素):
@Component({
templateUrl: 'my-widget.component.html',
selector: 'my-widget'
})
export class MyWidgetComponent implements OnInit, OnDestroy {
// Enum type variable to keep state
state: MyWidgetStateType;
// This is needed to be able to use the enum type in the template
private myWidgetStateType = MyWidgetStateType;
// Keep a reference to the observable to unsubscribe from it
private sub: Subscriber<any>;
constructor(public myWidgetService: MyWidgetService) {
}
ngOnInit(): void {
this.sub = Subscriber.create(this.onStateChange);
this.myWidgetService.getState().subscribe(this.sub);
}
ngOnDestroy(): void {
// Unsubscribe here
this.sub.unsubscribe();
}
private onStateChange(state: MyWidgetStateType): void {
console.log('Widget state: ' + MyWidgetStateType[state]);
this.state = state;
}
}
问题是:为什么如果调用onStateChange函数,视图永远不会得到值更新?
当然这并没有阻碍我的工作,因为我有上面的解决方案,但我只是好奇。