我试图将现有的应用程序从使用Http更改为使用HttpClient,但是我有一个错误.
因此,在我的服务中,您现在可以看到新代码与已注释掉的旧代码:
constructor( // private http: Http private http: HttpClient ) { } getSidebar() { // return this.http.get('http://localhost:3000/sidebar/edit-sidebar') // .map(res => res.json()); return this.http.get('http://localhost:3000/sidebar/edit-sidebar'); }
在我的page.component.ts中我有这个
this.sidebarService.getSidebar().subscribe(sidebar => { this.sidebar = sidebar.content; // this does not work Now });
Property 'content' does not exist on type 'Object'.
但是,如果我console.log(侧边栏)我得到以下内容:
{_id: "59dde326c7590a27a033fdec",content: "<h1>sidebar here</h1>"}
那么问题是什么?
Http再次起作用,但HttpClient却没有.
您可以使用接口,类等指定要返回的类型.例如,您可以使用以下内容:
return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');
作为示例,补充工具栏可能被定义为:
interface Sidebar { _id: string; content: string; }
有关详细信息,请参阅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.
原文地址:https://www.jb51.cc/angularjs/143619.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。