gpt4 book ai didi

Angular 4 - Http 到 HttpClient - 对象类型上不存在属性 'someproperty'

转载 作者:太空狗 更新时间:2023-10-29 17:03:41 26 4
gpt4 key购买 nike

我正在尝试将现有应用程序从使用 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/47202177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com