Angular HTTP POST 未触发

mor*_*oro 1 post http asp.net-web-api angular

我在从 NG 应用程序向 ASP.NET Core WebAPI 进行简单调用时遇到问题。代码如下:

  this.http.post(actionUrl, credentialsDto)
  .map((data: Response) => {
    if (data !== null) {
      localStorage.setItem(this.tokenStorageKey, JSON.stringify(data));
    }
});
Run Code Online (Sandbox Code Playgroud)

我尝试记录我的“data”回调参数,但在 if 语句中添加对 console.log() 的调用不会产生任何结果(意味着我根本没有控制台输出)。同时,如果我在调用之前或之后添加 console.log() 调用,但在同一函数中,它们会完美执行。

有谁知道这里发生了什么事?我是一个JS新手,所以不要怪我。我正在使用 Angular 5 中的原生 HTTP 客户端。

提前致谢。

Sur*_*yan 6

您还需要订阅Observable. Observable如果您尚未订阅,则不会触发。

this.http.post(actionUrl, credentialsDto)
         .map((data: Response) => {
               if (data !== null) {
                  localStorage.setItem(this.tokenStorageKey, JSON.stringify(data));
               }

               return response;
          }).subscribe(response => /* something here */).
Run Code Online (Sandbox Code Playgroud)

从RxJS 5.5开始,你不能map像以前那样使用运算符。您需要在pipe函数内部使用它。

RxJS 5.5及更高版本的方法

this.http.post(actionUrl, credentialsDto)
         .pipe(map((data: Response) => {
               if (data !== null) {
                  localStorage.setItem(this.tokenStorageKey, JSON.stringify(data));
               }

               return response;
          })).subscribe(response => /* something here */).
Run Code Online (Sandbox Code Playgroud)