首页 > 解决方案 > 如何只订阅一次可观察的

问题描述

我正在尝试订阅两个 observable 并获取要存储在数组对象中的值。它工作正常,但我的问题是它重复了三次,我不明白。我在一项服务中这样做是为了创建一项新服务。下面是代码示例。我也想知道我可以使用 Promise 而不是 Angular 中的 observable 吗?或者我可以在获得价值后将 observable 转换为 promise 并解决?谢谢您的帮助

 addEmployeeData() {
    const employeeObservable = this.apiService.getEmployeeDataObservable();
    employeeObservable.subscribe({
      next: (res: any) => {
        let employee = res;
        const paramsObservable = this.apiService.getParamsObservable();
        pageParamsObservable.subscribe({
          next: (pageParams: any) => {

标签: angulartypescriptrxjsobservable

解决方案


是的,你可以像使用 Promises 一样使用 Observables:

async asyncAddEmployeeData(): Promise<any> {
  return this.apiService.getEmployeeDataObservable()
    .pipe(
      mergeMap(employeeData => this.apiService.getParamsObservable()
        .pipe(
          tap((paramsData): void => {
            // There is available data
            // from apiService.getEmployeeDataObservable()
            // as employeeData variable
            // and data from apiService.getParamsObservable()
            // as paramsData.
            // You can do in tap function all the same
            // as in next in the subscribe.
          }),
        )
      ),
    )
    .toPromise();
}

并像这里一样使用它:

async ngOnInit(): Promise<void> {
  // ngOnInit just for example.
  const someVariable = await this.asyncAddEmployeeData();
}

但是使用 Observable 的常规方式如下所示:

addEmployeeData(): Observable<any> {
  return this.apiService.getEmployeeDataObservable()
    .pipe(
      mergeMap(employeeData => this.apiService.getParamsObservable()
        .pipe(
          tap(paramsData => {
            // There is available data
            // from apiService.getEmployeeDataObservable()
            // as employeeData variable
            // and data from apiService.getParamsObservable()
            // as paramsData.
          }),
        )
      ),
      take(1), // Just if you need only first value, if not, please, remove this string.
    );
}

和订阅:

ngOnInit(): void {
  // ngOnInit just for example.
  this.subscription = this.addEmployeeData().subscribe();
}

不要忘记取消订阅以避免内存泄漏:

ngOnDestroy(): void {
  this.subscription.unsubscribe();
}

推荐阅读