我正在尝试将现有应用程序从使用 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(sidebar)
我会得到以下内容:
{_id: "59dde326c7590a27a033fdec", content: "<h1>sidebar here</h1>"}
那么问题出在哪里呢?
再一次,Http
可以工作,但 HttpClient
却不能。
最佳答案
您可以使用接口(interface)、类等指定返回的类型。例如,您可以使用如下所示的内容:
return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');
例如,侧边栏可能定义为:
interface Sidebar {
_id: string;
content: string;
}
参见Typechecking the response从 Angular 文档获取更多信息:
...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.
关于Angular 4 - Http 到 HttpClient - 对象类型上不存在属性 'someproperty',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47484875/