A. *_* A. 1 subscribe observable angular2-routing angular angular5
我在ngOnInitcontroller.ts 中订阅了一种方法。从视图中,有一个选项可以从列表中选择不同的用户,这些用户重定向到同一页面,只是 URL 中的 ID 发生了变化。因此ngOnInit被多次调用。因此方法被多次订阅。我们多次选择不同的用户方法被调用为每个选择的成员数量,即如果我们选择 3 个用户一个接一个的路由被更改 3 次因此当 observable 获得结果时方法被调用 3 次。但是如果我们刷新页面一切正常。但是如果我使用 unsubscribe inngDestroy那么它就不会在ngOnInit. 有什么解决办法吗。
ngOnInit() {
this._myService.detailsReceived.subscribe((obj: details) =>
{console.log(obj.text)}
);
}
Run Code Online (Sandbox Code Playgroud)
同一页面上的路线变化是
this.route.navigate(['user-home', userid]);
Run Code Online (Sandbox Code Playgroud)
我需要这种方法保持订阅直到用户注销,因此不能使用 subscribe.Take(1)
但是如果我在 ngDestroy 中使用了 unsubscribe 那么它就不会在 ngOnInit 中再次被订阅
来自评论:
ngOnDestroy() { this._myService.detailsReceived.unsubscribe(); }我用过这个。取消订阅是错误的方式吗?
您没有正确取消订阅。你必须退订从Subscription,不是的Observable。取消订阅 observable 会导致您描述的行为。
// import
import { Subscription } from 'rxjs';
///////
// In the component
detailRecivedSubscription: Subscription;
ngOnInit() {
this.detailRecivedSubscription = this._myService.detailsReceived.subscribe((obj: details) =>
{console.log(obj.text)}
);
}
ngOnDestroy() {
this.detailRecivedSubscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
同样在这种情况下,在/a 根级别组件中订阅此服务也可能更有意义。