Angular-在Http.post中接收并返回Observable <T>响应

Yas*_* K. 3 observable rxjs typescript angular rxjs6

我实现了一个返回Observable的方法。在此方法内部,我使用http.post向后端发送请求。接收到响应(它是一个JSON对象)后,我要将其存储在Observable变量中并返回该变量。但是我不知怎么解决了那个问题。在.subscribe中,res变量没有存储在postResponse变量中,但是我可以在“本地” console.log中看到res变量具有正确的值。全局console.log为空。此外,我得到了错误:

错误“ TS2322:类型'ArqResponse'无法分配为类型'可观察'”返回错误。

我的代码如下所示:

postARQRequest(request): Observable<ArqResponse>{
    let postResponse = new ArqResponse;
    const result = this.http.post<ArqResponse>(this.arqUrl, request)
                       .subscribe((res: ArqResponse) => { postResponse = res; console.log('shadow: ' + res)});
    console.log('global: ' + JSON.stringify(postResponse));
    return postResponse;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 如何将响应主体存储在变量中,然后可以将其返回?
  2. 如何将ArqResponse变量“投射”到Observable变量?
  3. .subscribe 似乎是错误的,因为我得到:

this.arqService.postARQRequest(...)。subscribe不是函数错误

Tho*_*sen 5

我猜这就是你想要的:

postARQRequest(request): Observable<ArqResponse>{
    return this.http.post<ArqResponse>(this.arqUrl, request);
}
Run Code Online (Sandbox Code Playgroud)

无需在此处订阅任何内容。给定this.http.post返回所需的类型,只需返回该类型即可。

如果您确实想将响应存储在本地变量中,则可以通过以下几种方法进行:

请改用Promise,以获得结果。使用以下内容使其可观察of

async postARQRequest(request): Observable<ArqResponse>{
    let postResponse = new ArqResponse;
    postResponse = await this.http.post<ArqResponse>(this.arqUrl, request).toPromise();

    return of(postResponse);
}
Run Code Online (Sandbox Code Playgroud)

使用tap运算符对响应做出反应,但不对其进行突变

postARQRequest(request): Observable<ArqResponse>{
    return this.http.post<ArqResponse>(this.arqUrl, request).pipe(
        tap((res) => ...) // do stuff with res here, but it won't be mutated
    );
}
Run Code Online (Sandbox Code Playgroud)

使用map运算符将响应映射到其他内容

postARQRequest(request): Observable<ArqResponse>{
    return this.http.post<ArqResponse>(this.arqUrl, request).pipe(
        map((res) => ...) // do stuff with res here, but it *will map to whatever you return from this handler*
   );
}
Run Code Online (Sandbox Code Playgroud)