我试图将现有的应用程序从使用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.