如何获得管道的返回值?

时间:2019-06-19 07:32:29

标签: rxjs observable

我有create(newItem)方法,该方法在数据库上创建项目并返回id(Observable)和getDetails(id),该方法返回Observable

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';

create(input: Input | null | undefined): Observable<number> {
    let url_ = this.baseUrl + "/api/services/app/create";
    url_ = url_.replace(/[?&]$/, "");

    const content_ = JSON.stringify(input);

    let options_ : any = {
        body: content_,
        observe: "response",
        responseType: "blob",
        headers: new HttpHeaders({
            "Content-Type": "application/json", 
            "Accept": "application/json"
        })
    };

    return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => {
        return this.processCreateAsync(response_);
    })).pipe(_observableCatch((response_: any) => {
        if (response_ instanceof HttpResponseBase) {
            try {
                return this.processCreateAsync(<any>response_);
            } catch (e) {
                return <Observable<number>><any>_observableThrow(e);
            }
        } else
            return <Observable<number>><any>_observableThrow(response_);
    }));
}

我试图调用create方法并从create方法获取ID并使用此ID获取详细信息。

 this._dataService.create(newItem)
            .pipe(
                switchMap( id => {
                    return this._dataService.getDetails(id);

                })
             )
            .subscribe(result => {
                // Do stuff with result
                },
                error => {
                    console.log(error);
                }));

但是在switchMap中出现“未定义ID”错误 如何从create方法获取返回值并传递给getDetails方法?

2 个答案:

答案 0 :(得分:0)

在您的代码示例中,result中的变量subscribe应该包含id的值。

答案 1 :(得分:0)

我将rxjs降级为6.2.0,将@ types / node降级为10.1.4,现在可以正常工作。