我在一个angular应用程序中看到了以下代码。在代码中,Subscription
被用于subscribe
和unsubscribe
。我不明白为什么要用Subscription
。使用这种模式有什么好处吗?
public routeChangeSub$: Subscription;
this.routeChangeSub$ = this.route.firstChild.paramMap
.subscribe((map: ParamMap) =>
this.getRouteParams(map));
this.routeChangeSub$.unsubscribe();
getRouteParams(map: ParamMap): number {
const characterId = map.get('id');
let id: number = null;
if (characterId) {
this.character$ = this.store.pipe(
select(selectCharacterById, { id: characterId })
);
id = parseInt(characterId, 10);
}
return id;
}
更新:
这与有何不同
this.route.firstChild.paramMap
.subscribe((map: ParamMap) =>
this.getRouteParams(map));
getRouteParams(map: ParamMap): number {
const characterId = map.get('id');
let id: number = null;
if (characterId) {
this.character$ = this.store.pipe(
select(selectCharacterById, { id: characterId })
);
id = parseInt(characterId, 10);
}
return id;
一个可观察的(route.firstChild.paramMap
的类型(不会发射任何东西,除非订阅了它。
在这个文件中,作者明确订阅了paramMap
,通过调用getRouteParams()
来触发状态更改。然后他们立即取消订阅。如果他们没有取消订阅,订阅将继续运行,这可能会导致状态问题和内存泄漏。
一个简单得多的解决方案是使用take(1)
运算符。这将获取一个已发出的值(1
是要获取的值的数量(,然后将向订阅发送complete
信号。这将导致订阅自动取消订阅。
this.route.firstChild.paramMap.pipe(
take(1),
tap(map=>this.getRouteParams(map))
).subscribe();
因为我们使用的是take()
,所以不需要将订阅分配给属性。observable将发出一个值,并在取消订阅之前调用getRouteParams()
。
注意:如果您不知道,如果您想将效果应用于可观察对象之外的任何状态属性,则tap()
是要使用的运算符。