Angular 4 - Http to HttpClient - property 'someproperty' does not exist on type Object Angular 4 - Http 到 HttpClient - 属性 'someproperty' 在类型 Object 上不存在
Angular 4 - Http to HttpClient - property 'someproperty' does not exist on type Object Angular 4 - Http 到 HttpClient - 属性 'someproperty' 在类型 Object 上不存在
我正在尝试将一个现有的应用程序从使用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; // 现在无法工作 });
然而,对于我上面注释掉的那一行,我现在得到了这个错误:
属性'content'在类型'Object'上不存在。
然而,如果我console.log(sidebar)
,我得到以下结果:
{_id: "59dde326c7590a27a033fdec", content: "sidebar here
"}
那么问题是什么?
再一次,Http
可以工作,但是HttpClient
不能工作。
问题的原因是在使用Angular 4中的HttpClient进行Http请求时,返回的数据类型为Object,而Object类型没有定义someproperty属性,导致编译错误。
解决方法是通过指定返回类型来解决此问题。可以使用接口、类等来指定返回类型。例如,可以使用以下方式指定返回类型:
return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');
其中,Sidebar可以定义为:
interface Sidebar { _id: string; content: string; }
在Angular文档的Typechecking the response部分中有进一步的信息:
...TypeScript会正确地指出来自HTTP的Object没有results属性。这是因为虽然HttpClient将JSON响应解析为Object,但它不知道该对象的形状。
如果没有指定<Type>
,则默认返回类型为any
。
Angular 4中使用HttpClient替代了Http模块,但在切换模块后,可能会出现一些问题。比如,在使用HttpClient时,可能会遇到一个错误:"property 'someproperty' does not exist on type Object"。下面将解释这个问题出现的原因,并提供解决方法。
问题的原因是,当使用HttpClient发送请求并接收响应时,响应的类型被默认为Object类型。因此,如果在接收响应后,直接使用该对象的属性,编译器会报错,因为Object类型没有该属性。
要解决这个问题,可以通过为变量指定一个接口,明确告诉它会接收什么类型的值,或者给它一个初始值,以避免在编译时出错。
下面是解决方法的示例代码:
this.sidebarService.getSidebar().subscribe((sidebar: any) => { this.sidebar = sidebar.content; });
在上述代码中,通过为sidebar变量指定类型为any,告诉编译器它可以接收任何类型的值。然后,将接收到的响应中的content属性赋值给sidebar变量。
通过以上的解决方法,可以避免出现"property 'someproperty' does not exist on type Object"的错误。在使用HttpClient时,如果遇到类似的错误,可以按照上述方法进行解决。
Angular 4中的Http模块已经被HttpClient模块取代。在使用HttpClient模块时,当解析JSON响应为对象时,对象的结构是未知的,这就是Typescript显示错误的原因。
为了解决这个问题,我们可以使用方括号表示法。具体的解决方法如下所示:
this.sidebarService.getSidebar().subscribe(sidebar => { this.sidebar = sidebar["content"]; });
以上就是解决该问题的方法。在这个方法中,我们使用方括号表示法将响应的内容赋值给变量`this.sidebar`,以避免Typescript的错误提示。