Angular 4-从Http到HttpClient-对象类型上不存在属性'someproperty' [英] Angular 4 - Http to HttpClient - property 'someproperty' does not exist on type Object
问题描述
我正在尝试将现有应用程序从使用Http
更改为使用HttpClient
,但是我遇到了错误.
I am trying to change an existing app from using Http
to using HttpClient
, however i have an error.
因此,在我的服务中,您现在可以看到新代码与已注释掉的旧代码:
So in my service now you can see the new code vs the old code that's been commented out:
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
});
但是对于上面我评论过的那一行,我现在得到此错误:
However for the line above which I commented on I get this error now:
Property 'content'
does not exist on type 'Object'.
但是,如果我console.log(sidebar)
我得到以下信息:
However if I console.log(sidebar)
I get the following:
{_id: "59dde326c7590a27a033fdec", content: "<h1>sidebar here</h1>"}
那是什么问题?
再次,Http
有效,但HttpClient
无效.
推荐答案
您可以使用接口,类等指定要返回的类型.例如,您可以使用类似以下的内容:
You can specify the type that is being returned, using an interface, class, etc. For example, you can use something like the following:
return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');
例如,补充工具栏可以定义为:
As an example, Sidebar might be defined as:
interface Sidebar {
_id: string;
content: string;
}
请参阅Angular文档中的对响应进行类型检查,以了解更多信息:>
See Typechecking the response from the Angular docs for further information:
... TypeScript会正确地抱怨从HTTP返回的对象没有results属性.这是因为,当HttpClient将JSON响应解析为一个对象时,它不知道该对象是什么形状.
...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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!