多次调用订阅方法 Angular 5
Subscribe method get call multiple times Angular 5
我在 controller.ts 的 ngOnInit
中订阅了一种方法。从视图中,有一个选项 select 来自列表的不同用户重定向到同一页面只是来自 URL 的 ID 被更改。因此 ngOnInit
被多次调用。因此方法被多次订阅。很多次,我们 select 为成员 selected 的每个号码调用不同的用户方法,即如果我们 select 3 个用户一个接一个地更改路由 3 次,因此方法被调用 3如果我们刷新页面,observable 获得 result.But 的时间一切正常。但是,如果我在 ngDestroy
中使用取消订阅,那么它将不会在 ngOnInit
中再次订阅。有什么解决办法吗。
ngOnInit() {
this._myService.detailsReceived.subscribe((obj: details) =>
{console.log(obj.text)}
);
}
同一页面上的路线更改为
this.route.navigate(['user-home', userid]);
我要求此方法保持订阅状态直到用户注销,因此不能使用 subscribe.Take(1)
but if I used unsubscribe in ngDestroy then it won't get subscribed again in ngOnInit
来自评论:
ngOnDestroy() { this._myService.detailsReceived.unsubscribe(); }
I used this. Is it wrong way to 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();
}
此外,在这种情况下,在 the/a 根级组件中订阅该服务也可能更有意义。
我在 controller.ts 的 ngOnInit
中订阅了一种方法。从视图中,有一个选项 select 来自列表的不同用户重定向到同一页面只是来自 URL 的 ID 被更改。因此 ngOnInit
被多次调用。因此方法被多次订阅。很多次,我们 select 为成员 selected 的每个号码调用不同的用户方法,即如果我们 select 3 个用户一个接一个地更改路由 3 次,因此方法被调用 3如果我们刷新页面,observable 获得 result.But 的时间一切正常。但是,如果我在 ngDestroy
中使用取消订阅,那么它将不会在 ngOnInit
中再次订阅。有什么解决办法吗。
ngOnInit() {
this._myService.detailsReceived.subscribe((obj: details) =>
{console.log(obj.text)}
);
}
同一页面上的路线更改为
this.route.navigate(['user-home', userid]);
我要求此方法保持订阅状态直到用户注销,因此不能使用 subscribe.Take(1)
but if I used unsubscribe in ngDestroy then it won't get subscribed again in ngOnInit
来自评论:
ngOnDestroy() { this._myService.detailsReceived.unsubscribe(); }
I used this. Is it wrong way to 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();
}
此外,在这种情况下,在 the/a 根级组件中订阅该服务也可能更有意义。