Angular2 / Typescript编译错误:property' body'在类型'响应'中不存在

时间:2016-08-19 19:28:54

标签: typescript

getVerificationCode(phoneNumber) {
        let url = `${remote}/auth/phoneNumber/${phoneNumber}`;
        return this._http.get(url)
            .toPromise()
            .then(result => {
               console.log(result.body);  <--- ERROR
            });
      }

在结果返回的上面的代码中,它有一个名为body的属性。 但是,typescript编译器会抛出以下错误:

Error TS2339: Property 'body' does not exist on type 'Response'.

不确定如何解决这个问题。

我尝试定义类型

的接口
interface ResultData<T> {
  body: string
}

然后将其用作:

this.getVerificationCode('1111111') {
    let url = `${remote}/auth/phoneNumber/${phoneNumber}`;
     return this._http.get(url)
           .toPromise()
           .then( (result: ResultData<any> )=> {
                   console.log(result.body);  <--- ERROR
                });

然后我会收到以下错误:

Error TS2345: Argument of type '(result: ResultData<any>) => void' is not assignable to parameter of type '(value: Response) => void | PromiseLike<void>'.
  Types of parameters 'result' and 'value' are incompatible.
    Type 'Response' is not assignable to type 'ResultData<any>'.
      Property 'body' is missing in type 'Response'.

1 个答案:

答案 0 :(得分:0)

试试吧

getVerificationCode(phoneNumber) {
    let url = `${remote}/auth/phoneNumber/${phoneNumber}`;
    return this._http.get(url)
        .toPromise()
        .then((result: Object) => {
           console.log(result.body);  <--- ERROR
        });
  }