假设我有这个可观察的:
public settings$: Observable<
SettingsResponse
> = this._service.getSettings();
然后我有:
public ngOnInit(): void {
window.customService.init();
}
因为 init 在 observable 完成之前触发,所以在 window.customService.init()
之前,除了 setTimeout 或订阅 observable 并使用非异步属性在模板中设置设置之外,还有其他方法可以延迟吗?触发?
最佳答案
您可以tap进入可观察的,并使用 share这样对于许多async
管道来说,只执行一个选项卡。
public settings$: Observable<SettingsResponse> = this._service.getSettings().pipe(
tap(()=> this.init()),
share()
);
public init() {
if (!this.initFlag) {
window.customService.init();
this.initFlag = true;
}
}
您还可以使用scan运算符,而不必跟踪该函数是否已被调用。
public settings$: Observable<SettingsResponse> = this._service.getSettings().pipe(
scan((acc, next)=> (acc === "first" && this.init(), next), "first"),
share()
);
public init() {
window.customService.init();
}
如果您只需要第一个发出的值,那么我会使用 finalize改为运算符。我认为它仍然会使用 async
触发,但我从未尝试过。
public settings$: Observable<SettingsResponse> = this._service.getSettings().pipe(
first(),
finalize(() => window.customService.init()),
shareReplay(1)
);
关于angular - 如何等待异步管道完成并在之后调用另一个函数,而不订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56449178/