点(例如 reponse.title)属性 无法处理从 angular 中的 http 服务获取的响应对象 2

dot (eg. reponse.title) property is not working on response object got from http service in angular 2

我在 angular 2 中收到来自 http 服务的响应对象,如果我尝试控制台 response.prop,它不工作并且显示以下错误:

D:/ABC/angular-training/angular_cli/src/app/shared/footer/footer.component.ts (16,28): Property 'prop' does not exist on type '{}'.)

但是当我响应["prop"]时,我得到了我的价值。

这是我的代码:

export class FooterComponent {
  constructor(private httpService : HttpService) {
  this.httpService.getData("http://127.0.0.1:8887/footer.json").then(response => {
      console.log(response);//shows object 
      console.log(response.prop);//not works
      console.log(response["prop"]);//works fine
    });
  }
}

这是我的 Httpservice 代码:

export class HttpService {
private Title = URL;// URL to web api

constructor(private http: Http) { } 

getData(url="this.Title"): Promise<{}> {
return this.http.get(url)
           .toPromise()
           .then(response => 
             response.json()
           )
           .catch(this.handleError);
}

private handleError(error: any): Promise<any> {
console.error('An error occurred', error); 
return Promise.reject(error.message || error);
}
}

这也是来自服务器的 JSON 响应:

{
"footerLinks"  : {
  "social":[{
    "text":"Google",
    "link":"www.google.com"
  },
  {
    "text":"Facebook",
    "link":"www.facebook.com"
  },
  {
    "text":"Twitter",
    "link":"www.Twiiter.com"
  },
 {
    "text":"Pinterest",
    "link":"www.Pinterest.com"
  },
  {
    "text":"LinkedIn",
    "link":"www.linkedin.com"
  }]

}
} 

你需要声明response的类型。

试试下面,

response =>

to

(response : {prop: <string or what ever type>}) =>

这样 Typescript 编译器就会知道您的响应对象的类型。

希望对您有所帮助!!

您的回复可能看起来像 json 但实际上是一个字符串。

检查类型

console.log(typeof response);

也试试..

response.json()

JSON.parse(response);

您可能需要在服务器响应中添加 JSON 响应 header。

如前所述,您的响应是一个对象(在对象内部),这就是为什么您需要使用 console.log(response["prop"]); 访问数据,因为这是我们访问嵌套对象的方式。

不知道你想从你的响应中提取什么,如果你只想要数组,这样做:

服务:

getData(url="this.Title"): Promise<{}> {
   return this.http.get(url)
      .toPromise()
      .then(response => response.json().footerLinks['social'])
      .catch(this.handleError);
}

如果要保留包含数组的对象 social,只需将 ['social'] 从上面的代码中删除即可。但我假设您只需要数组,因为对象 social 实际上不包含数组以外的任何内容。

组件:

links: any[] = [];

this.httpService.getData("http://127.0.0.1:8887/footer.json")
  .then(response => {
     this.links = response;
  });
}

你可以迭代数组:

<div *ngFor="let link of links">
  {{link?.text}} {{link?.link}}
</div>

请注意,我使用了 safe navigation operator,它可以防止应用程序在空值的情况下抛出错误。