使用rxjs通过管道运算符获取更多详细信息

时间:2018-11-30 10:49:55

标签: angular rxjs angular-services rxjs-pipeable-operators

在服务中,我想要一个对象,但在将单个对象返回到组件之前,我还想要该对象的详细信息。

使用管道运算符,我尝试调用向我提供详细信息的函数(在本例中为Bar)。

但是我有点迷茫,因为我返回observable<Bar>而不是Bar

export class Foo {
  public ID;
  public Bar: Bar;
}

export class Bar { }

  /**
  * Returns a single Foo
  */
  public FindSingleFoo(fooID: string): Observable<Foo | HttpError> {
    return this._httpClient.post<Foo>('API/FindSingleFoo', fooID)
      .pipe(
        map((data) => this.FindBarOfFoo(data)),
      );
  }

   /**
   * Returns the Bar of Foo
   * @param fooID - the ID you want Bar for
   */
  public FindBarOfFoo(foo: Foo): Observable<Foo | HttpError> {
    return this._httpClient.post<Bar>('API/FindBarOfFoo', foo.ID).subscribe(
      (result: Bar) => foo.Bar = result
    );
  }

2 个答案:

答案 0 :(得分:2)

我认为您应该使用switchMap而不是map

尝试一下:

export class Foo {
  public ID;
  public Bar: Bar;
}

export class Bar {}

import { map, switchMap } from 'rxjs/operators';

public FindSingleFoo(fooID: string): Observable<Bar|HttpError> {
  return this._httpClient.post<Foo>('API/FindSingleFoo', fooID)
    .pipe(
      switchMap(data => this.FindBarOfFoo(data)),
    );
}

public FindBarOfFoo(foo: Foo): Observable <Bar|HttpError> {
  return this._httpClient.post<Bar>('API/FindBarOfFoo', foo.ID);
}

答案 1 :(得分:-2)

尝试一下,我认为这会起作用

public FindSingleFoo(fooID: string): Observable<Foo> {
    return this._http.post<Foo>('API/FindSingleFoo', fooID)
        .pipe(
            map((data) => this.FindBarOfFoo(data)),
            //map(data => data)
        );
}

/**
* Returns the Bar of Foo
* @param fooID - the ID you want Bar for
*/
public FindBarOfFoo(foo: Foo): Foo {
    let X = null;
    this._http.post<Bar>('API/FindBarOfFoo', foo.ID).subscribe(
        data => { X = data }
    );
    return X;
}