http - angular2 如何将来自 http.get 的响应头数据存储在额外变量中?

标签 http angular get header response

我对 Angular 2 和 Typescript 还很陌生,想构建一个卡片搜索应用程序。 基本上我有一个存储和观察响应数据的组件......

this.searchFormGroup.valueChanges
  .debounceTime(200)
  .distinctUntilChanged()
  .switchMap(searchFormGroup => this.mtgService.getCardsByName(searchFormGroup))
    .subscribe(
      searchResult => { 
        this.searchResult = searchResult.cards;
      },
      err => {
        console.log(err);
      });

...和一个服务,它将 http.get 请求发送到 API ...

getCardsByName(searchFormGroup){
   this.params.set(...) ...

   return this.http.get(this.nameUrl, { search: this.params })
     .map(res => res.json())
     .catch((error:any) => Observable.throw(error.json().error || 'Server error'))}

...相互交流。

在组件内存储来自请求的 header 数据的最佳方式是什么?基本上我需要请求的总卡数和分页链接,它们在响应 header 中可用。几个小时以来,我一直在努力寻找解决方案 :o

最佳答案

好的尝试和错误让我解决了这个问题: 组件激活服务的 http.get -> 服务响应 res.json() -> 组件仅在 JSON 中获得 res,似乎删除了响应 header 。 我的解决方法是:

组件:

this.searchFormGroup.valueChanges
  .debounceTime(200)
  .distinctUntilChanged()
  .switchMap(searchFormGroup => this.mtgService.getCardsByName(searchFormGroup))
    .subscribe(
      res => { 
        console.log(res.headers); //works fine now!
        this.searchResult = res.json().cards;
      },
      err => {
        console.log(err);
      });

服务:

getCardsByName(searchFormGroup){
   this.params.set(...) ...

   return this.http.get(this.nameUrl, { search: this.params })
     .catch((error:any) => Observable.throw(error.json().error || 'Server error')) }

所以完整的资源现在被传递回组件。

但是:有什么技巧可以使它变得更好吗?

关于http - angular2 如何将来自 http.get 的响应头数据存储在额外变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290241/

相关文章:

angular - 如何将 Angular Universal 发布到 azure 网站?

java - 提取使用 HTTP GET 请求下载的 Zip 文件的内容

http - "/users"和 "/users/"应该指向同一个(RESTful)资源吗?

c# - 通过 HTTP 向客户端发送字节数组时操作缓慢且无响应主体

javascript - ajax 请求获取 'canceled' 现在网站已上线

javascript - 如何将 HTML 保存到变量中

javascript - 通过输入在 highcharts 中显示多个 csv 文件

search - ElasticSearch POST with json search body vs GET with json in url

javascript - AngularJS $http GET 请求本地 JSON 文件返回 SyntaxError : Unexpected token ]

javascript - 使用 AngularJS 将 JSON 数据保存到服务器 - 在页面刷新时消失