我使用订阅从Angular 路线中获取一个参数。下面是代码:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription} from 'rxjs';
@Component({
selector: 'farm-house',
templateUrl: './house.component.html',
styleUrls: ['./house.component.scss']
})
export class GreenhouseComponent implements OnInit, OnDestroy {
private routeSub: Subscription;
id: string;
constructor(private route: ActivatedRoute) {
this.id = "";
}
ngOnInit(): void {
this.routeSub = this.route.params.subscribe(params => {
this.id = params['id'];
});
}
ngOnDestroy() {
this.routeSub.unsubscribe();
}
}
但问题是编译器会说:
属性“routeSub”没有初始值设定项,并且未在构造函数中明确赋值。
我的问题是,初始化Subscription对象的最佳方法是什么?
6条答案
按热度按时间oxiaedzo1#
我提出了另一个解决方案,它使用this question中的
Subscription.EMPTY
。nhaq1z212#
大多数情况下,它的应该是足够的检查订阅之前取消订阅.
在您的情况下,不需要初始化订阅,因为您已经在
ngOnInit()
中调用了subscribe方法。可能会出现错误,因为您直接在 Subscription 上调用unsubscribe()
,而没有检查它是否已初始化。tzxcd3kk3#
应该只是
第一个月
这对我很有效。
t5fffqht4#
如果你声明了
routeSub: any;
,编译器不会抱怨。看到它在这个职位上完成,我为我工作gjmwrych5#
方式一:
我只订阅了一份。
第二种方法,如果我有多个订阅,我会用一次清理来清理它们:
第三条路----大多是最好的路
这最后一个过程与onPush一起工作,你永远不会忘记取消订阅。
请注意,第一种方式是非常方便的,当您订阅和取消订阅作为呼叫的一部分,甚至与第二种方式相结合:
sg24os4d6#
这里不需要取消订阅,因为Angular会为您销毁此特定订阅。