【问题标题】:Can't map the response to the object无法将响应映射到对象
【发布时间】:2017-10-05 10:14:47
【问题描述】:

我正在尝试将 Angular4 HttpClient 与我定义的可观察对象一起使用。不幸的是,我似乎无法将响应映射到对象。

问题似乎是我正在使用 httpclient(它隐式返回 json,因此没有 response.json() 函数),据我所知,http 已被弃用?无论如何,因此 response.json() 会导致错误; 错误类型错误:response.json 不是函数

代码;

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

import {Observable} from 'rxjs/Observable';
import {JsonpModule, Jsonp, Response} from '@angular/http';

export class BucketList {
  constructor(public name: string,
              public creationdate: string) {
  }
}

@Injectable()
export class DocumentSearchService {

    constructor(private _http : HttpClient) { }

    getBucketList () : Observable<BucketList> {

      let serviceURL = "http://localhost:3000/listBuckets";

      return this._http.get(serviceURL, {withCredentials: true, responseType: 'json'})

      .map((response: Response) => <BucketList>(response.json())
      .catch((error: any) => window.console.log(error)));
    }
}

ngOnInit() {
// this.BucketList = this.DocumentSearchService.getBucketList

   this.BucketList = 
   this.DocumentSearchService.getBucketList().subscribe(value => {
}

有人能指出我正确的方向吗?到目前为止,在 SO 上进行谷歌搜索和搜索都没有得到任何答案......

谢谢。

【问题讨论】:

标签: json angular


【解决方案1】:

responseType: 'json'response.json() 可以省略,因为它们是隐含的by default

responseType 值决定了如何解析成功的响应正文。如果 responseType 是默认的 json,则结果对象的类型接口可以作为类型参数传递给 request()。

<...>

get<T>(url: string, options: {
    headers?: HttpHeaders,
    observe: 'events',
    params?: HttpParams,
    reportProgress?: boolean,
    responseType?: 'json',
    withCredentials?: boolean,
  }): Observable<HttpEvent<T>>

构造一个将正文解释为 JSON 并返回完整事件流的 GET 请求。

【讨论】:

  • 非常感谢大家的意见。它现在工作得非常好:-) @Injectable() export class DocumentSearchService { constructor(private _http : HttpClient) { } getBucketList () : Observable { let serviceURL = "localhost:3000/listBuckets";返回 this._http.get(serviceURL); } }
猜你喜欢
  • 2020-08-08
  • 2019-07-22
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2017-12-16
  • 2017-01-17
  • 2017-11-03
  • 2019-09-24
相关资源
最近更新 更多