停止共享数据服务的可观察流 Angular
Stop observable stream of shared data service Angular
我有这项服务可以在我的应用程序的组件之间共享数据:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
private source = new BehaviorSubject<any>('');
data = this.source.asObservable();
constructor() { }
update(values: any) {
this.source.next(values);
}
}
从组件中,我像这样更新数据:
this.dataSvc.update(this.data);
假设 this.data 是一个对象。
我从另一个组件订阅了服务
this.dataSvc.data.subscribe(
data => let object = data,
error => console.log(error),
() => console.log('complete')
);
从未调用完整方法。
如何调用完整方法并停止订阅?
我试图在 next in service 之后添加 this.source.complete()
。没用
谢谢
Observable 永远不会完成的原因是您永远不会取消订阅它。
您可以使用像 takeUntil
这样的运算符(如果有特定条件您想取消订阅),但我觉得您只需要在组件被销毁时清理您的订阅。以下是如何执行此操作的几个选项:
当组件被销毁时,您可以使用ngOnDestroy
生命周期钩子取消订阅。
试试这个:
subscription: Subscription;
/* using ngOnInit life cycle hook for the example,
but you could assign the subscription anywhere */
ngOnInit() {
this.subscription = this.dataSvc.data.subscribe( //.. )
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
问题是您正在设置订阅,但从未清理过它,因此 Observable 永远不会 "completes"。上面的代码将解决这个问题。
或者,如果您只需要模板中的数据而不是组件中的数据 class,您可以使用 async
管道。
在您的 component.ts
文件中:
data$: Observable<Data>;
ngOnInit() {
this.data$ = this.dataSvc.data;
}
然后在您的模板中:
<p> {{ data$ | async }} </p>
当您的组件被销毁时,Angular 将为您处理所有清理工作:)
这里有一些关于 life cycle hooks, the unsubscribe
method, and the async
pipe 的链接。
我有这项服务可以在我的应用程序的组件之间共享数据:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
private source = new BehaviorSubject<any>('');
data = this.source.asObservable();
constructor() { }
update(values: any) {
this.source.next(values);
}
}
从组件中,我像这样更新数据:
this.dataSvc.update(this.data);
假设 this.data 是一个对象。
我从另一个组件订阅了服务
this.dataSvc.data.subscribe(
data => let object = data,
error => console.log(error),
() => console.log('complete')
);
从未调用完整方法。
如何调用完整方法并停止订阅?
我试图在 next in service 之后添加 this.source.complete()
。没用
谢谢
Observable 永远不会完成的原因是您永远不会取消订阅它。
您可以使用像 takeUntil
这样的运算符(如果有特定条件您想取消订阅),但我觉得您只需要在组件被销毁时清理您的订阅。以下是如何执行此操作的几个选项:
当组件被销毁时,您可以使用ngOnDestroy
生命周期钩子取消订阅。
试试这个:
subscription: Subscription;
/* using ngOnInit life cycle hook for the example,
but you could assign the subscription anywhere */
ngOnInit() {
this.subscription = this.dataSvc.data.subscribe( //.. )
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
问题是您正在设置订阅,但从未清理过它,因此 Observable 永远不会 "completes"。上面的代码将解决这个问题。
或者,如果您只需要模板中的数据而不是组件中的数据 class,您可以使用 async
管道。
在您的 component.ts
文件中:
data$: Observable<Data>;
ngOnInit() {
this.data$ = this.dataSvc.data;
}
然后在您的模板中:
<p> {{ data$ | async }} </p>
当您的组件被销毁时,Angular 将为您处理所有清理工作:)
这里有一些关于 life cycle hooks, the unsubscribe
method, and the async
pipe 的链接。