【发布时间】:2019-01-09 12:28:55
【问题描述】:
假设一个组件具有以下属性:
private foo$: Observable<Array<SomeType>>;
private bar: SomeOtherType;
后来他们得到了价值......
this.foo$ = someSubject.pipe(switchMap(...whatever...
this.bar = new SomeOtherType(...whatever...
在某些时候,无论出于何种原因,我都想清空这两个属性,清空是指删除它们的值,所以将它们设置回它们获得值之前的状态。
让他们undefined 不是一个选项。如果我这样做,他们会丢失他们的“类型信息”。我希望 TypeScript 和 Angular 知道它们仍在处理 Observable 和 SomeOtherType 的对象。
我有什么选择?
【问题讨论】:
-
如果不是
undefined,“他们获得价值之前的状态”是什么? -
@ConnorsFan 这也是让我感到困惑的地方。因为一旦我设置了
foo$undefinedAngular 就不再将其视为一个 Observable 并且即使新值再次被推送到它的流中,它的订阅也将不再起作用。 -
看看this stackblitz。
obs变量在 5 秒后设置为undefined,并且 Observable 继续工作。 -
Angular 有 a tutorial 这与此处相关。它有一个live example。在 hero-search.component.ts 中查找方法
search(term: string)。在其正文中添加以下代码:if(term == 'undef') this.heroes$ = undefined;。在搜索框中输入“undef”。之后搜索功能停止工作。 -
视图使用这个循环来显示结果:
<li *ngFor="let hero of heroes$ | async" >。 Observable 可能会停止,因为当heroes$为undefined时,async管道没有任何可订阅的 Observable。当组件被销毁时,async管道 unsubscribes automatically,也可能在 observable 变量变为undefined时。
标签: angular typescript variables types undefined