小编Yas*_* K.的帖子

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

我实现了一个返回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不是函数错误

observable rxjs typescript angular rxjs6

3
推荐指数
1
解决办法
458
查看次数

标签 统计

angular ×1

observable ×1

rxjs ×1

rxjs6 ×1

typescript ×1