依次调用嵌套订阅

时间:2019-03-14 16:14:12

标签: angular rxjs rxjs6

调用一个彼此依赖的订阅方法

结构:

    this.example1().subscribe(res => {
      this.response = res;
    })


  example1(): Observable<any> | any {
    this.example2().pipe(
      catchError(err => {
        return throwError(err);
      })
    ).subscribe(res => {
       return of(res);
    });
  }

  example2(): Observable<any> | any {
     this.example3().pipe(
      catchError(err => {
        return throwError(err);
      })
    ).subscribe(res => {
      return of(res);
    });

  }

  example3() {
    return of('return from example 3');
  }

现在收到错误“无法读取未定义的属性'pipe'”

example3()正确返回值,但example2的值无法返回示例1

链接:stackblitz demo

2 个答案:

答案 0 :(得分:0)

example1()example2()函数不返回任何内容。只需添加return关键字即可返回您的Observable。

答案 1 :(得分:0)

您无需订阅example1(),example2(),example3()。
异步回调方法 subscribe 中的返回不是函数的返回。

  example1(): Observable<any> | any {
    console.log('1');
    return this.example2().pipe(
      catchError(err => {
        return throwError(err);
      })
    );
  }

  example2(): Observable<any> | any {
    console.log('2');
    return this.example3().pipe(
      catchError(err => {
        return throwError(err);
      })
    );
  }

  example3() {
    console.log('3');
    return of('return from example 3');
  }

StackBlitz

更新(15.03.2019) 加上您的评论,代码应为:

export class AppComponent {
  response;
  private init$: Observable<any>;

  public ngOnInit() {
    //get Data from remote
    this.example3().subscribe(value => {
      //Do primary somethimg with result
      let calcVal = value *2;
      // Do remote something with data
      this.example2(calcVal).subscribe(newValue => {
        // Result with updated data
        console.log(newValue);
        this.response = newValue;
      });
    });
  }

  // Async do something with data
  example2(value: number): Observable<string>{
    return of('Value is: ' + value);
  }

  // Async get data
  example3(): Observable<number> {
    console.log('3');
    return of(3);
  }

}

StackBlitz

或使用switchMap:

export class AppComponent {
  response;
  private init$: Observable<any>;

  public ngOnInit() {
    let obs = this.example3().pipe(switchMap(val => this.example2(val)));
    obs.subscribe(result => this.response = result);
  }

  // Async do something with data
  example2(value: number): Observable<string>{
    return of('Value is: ' + value);
  }

  // Async get data
  example3(): Observable<number> {
    console.log('3');
    return of(3);

}

StackBlitz