按顺序调用嵌套订阅

问题描述 投票:-2回答:2

调用一个依赖于另一个订阅方法的订阅

结构体:

    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');
  }

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

example3()正确返回值,但是从example2值返回到示例1

链接:stackblitz demo

angular rxjs rxjs6
2个回答
0
投票

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


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

© www.soinside.com 2019 - 2024. All rights reserved.