Angular 4 – Http到HttpClient – 属性’someproperty’在Object类型上不存在

前端之家收集整理的这篇文章主要介绍了Angular 4 – Http到HttpClient – 属性’someproperty’在Object类型上不存在前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将现有的应用程序从使用Http更改为使用HttpClient,但是我有一个错误.

因此,在我的服务中,您现在可以看到新代码与已注释掉的旧代码

  1. constructor(
  2. // private http: Http
  3. private http: HttpClient
  4. ) { }
  5.  
  6. getSidebar() {
  7. // return this.http.get('http://localhost:3000/sidebar/edit-sidebar')
  8. // .map(res => res.json());
  9. return this.http.get('http://localhost:3000/sidebar/edit-sidebar');
  10. }

在我的page.component.ts中我有这个

  1. this.sidebarService.getSidebar().subscribe(sidebar => {
  2. this.sidebar = sidebar.content; // this does not work now
  3. });

但是对于我评论过的行,我现在得到了这个错误

  1. Property 'content'
  2. does not exist on type 'Object'.

但是,如果我console.log(侧边栏)我得到以下内容

  1. {_id: "59dde326c7590a27a033fdec",content: "<h1>sidebar here</h1>"}

那么问题是什么?

Http再次起作用,但HttpClient却没有.

您可以使用接口,类等指定要返回的类型.例如,您可以使用以下内容
  1. return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');

作为示例,补充工具栏可能被定义为:

  1. interface Sidebar {
  2. _id: string;
  3. content: string;
  4. }

有关详细信息,请参阅Angular文档中的Typechecking the response

…TypeScript would correctly complain that the Object coming back from HTTP does not have a results property. That’s because while HttpClient parsed the JSON response into an Object,it doesn’t know what shape that object is.

猜你在找的Angularjs相关文章