【问题标题】:Angular HTTP POST not firingAngular HTTP POST 未触发
【发布时间】:2019-01-18 02:30:23
【问题描述】:

从我的 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 客户端。

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    您还需要订阅ObservableObservable 如果你没有订阅它就不会触发。

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

    【讨论】:

    • 使用这种方法,我应该在 subscribe 或 map 函数中做我的本地存储工作吗?简单地用订阅替换我的地图有意义吗?
    • 这取决于你的逻辑。如果您不更改响应,则可以将map 替换为tap
    • 基本上我的逻辑是将从服务器接收到的令牌存储在本地存储中。就是这样。
    • 所以看tap操作符如果你使用高于5.5,否则看do操作符
    • 对不起,我使用的版本是 5.5.7 并且没有“tap”操作符。在线我发现仅适用于 v6 或更高版本。 “做”也不起作用。我也应该像你一样在最后使用“订阅”吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多