Angular HTTP POST不触发

时间:2018-08-10 12:58:19

标签: angular http post asp.net-web-api

从NG应用程序向ASP.NET Core WebAPI进行简单调用时遇到麻烦。该代码是以下代码之一:

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

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

有人知道这里发生了什么吗?我是JS新手,所以不要怪我。 我正在使用Angular 5中的本机HTTP客户端。

谢谢。

1 个答案:

答案 0 :(得分:2)

您还需要订阅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 */).

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 */).