问题描述
我正在尝试将现有应用程序从使用 Http
更改为使用 HttpClient
,但是出现错误.
所以现在在我的服务中,您可以看到新代码与已注释掉的旧代码:
构造函数(//私有 http: Http私有 http: HttpClient) { }获取侧边栏(){//返回 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;//这现在不起作用});
但是对于上面我评论的行,我现在收到此错误:
属性内容"不存在于类型对象"上.
但是,如果我 console.log(sidebar)
我得到以下信息:
{_id: "59dde326c7590a27a033fdec", content: " sidebar here
"}
有什么问题吗?
再一次,Http
有效但 HttpClient
无效.
您可以指定返回的类型,使用接口、类等.例如,您可以使用以下内容:
return this.http.get('http://localhost:3000/sidebar/edit-sidebar');
例如,侧边栏可能定义为:
interface Sidebar {_id:字符串;内容:字符串;}
请参阅 Angular 文档中的对响应进行类型检查以获取更多信息:>
...TypeScript 会正确地抱怨从 HTTP 返回的对象没有 results 属性.这是因为当 HttpClient 将 JSON 响应解析为一个对象时,它不知道该对象是什么形状.
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');
}
And in my page.component.ts
I have this
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'.
However if I console.log(sidebar)
I get the following:
{_id: "59dde326c7590a27a033fdec", content: "<h1>sidebar here</h1>"}
So what's the issue?
Once again, Http
works but HttpClient
does not.
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;
}
See Typechecking the response from the Angular docs for further information:
这篇关于Angular 4 - Http 到 HttpClient - 类型 Object 上不存在属性“someproperty"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!