【问题标题】:angular2 How to store response header data from http.get in extra variable?angular2 如何将来自 http.get 的响应头数据存储在额外的变量中?
【发布时间】:2017-05-08 11:57:17
【问题描述】:

我对 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'))}

...相互交流。

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

【问题讨论】:

  • 你需要什么标题?
  • Link:, Page-Size, Count, Total-Count, Ratelimit-Limit 和 Ratelimit-Remaining 基本上。 GET 请求的 API URL 是 api.magicthegathering.io/v1/cards 例如
  • 在后端设置标头的最佳方式。
  • 我现在尽量避免构建后端 :(

标签: http angular get header response


【解决方案1】:

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

组件:

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')) }

所以现在将完整的 res 传递回组件。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2023-03-09
    • 2018-07-16
    • 1970-01-01
    相关资源
    最近更新 更多