Angular 4 – Http到HttpClient – 属性'someproperty'在Objecttypes上不存在
我试图改变现有的应用程序使用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
不。
您可以使用接口,类等来指定正在返回的types。例如,您可以使用类似下面的内容:
return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');
作为一个例子,边栏可能被定义为:
interface Sidebar { _id: string; content: string; }
请参阅Typechecking Angular文档的回复以获取更多信息:
… TypeScript将正确地抱怨从HTTP返回的对象没有结果属性。 这是因为虽然HttpClient把JSON响应parsing成一个Object,但它不知道这个对象是什么形状。
替代scheme:
this.sidebar = sidebar["content"];
这将返回HttpClient中的值,HttpClient自动parsingJSON响应到一个对象,该对象的形状是未知的,这就是为什么Typescript显示此错误
尝试将接口边栏添加到您的订阅方法:
this.sidebarService.getSidebar().subscribe((sidebar: Sidebar) => { this.sidebar = sidebar.content; }); interface Sidebar { _id?: string; content?: string; }
你可以给variables(侧边栏)分配一个接口来明确地告诉它将得到或分配给它,所以它不会抛出编译时错误。
this.sidebarService.getSidebar().subscribe((sidebar: any) => { this.sidebar = sidebar.content; });