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

Voj*_*vic 12 typescript angular

我正在尝试将现有应用程序从使用更改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');
    }
Run Code Online (Sandbox Code Playgroud)

在我,page.component.ts我有这个

this.sidebarService.getSidebar().subscribe(sidebar => {
                        this.sidebar = sidebar.content; // this does not work now
                    });
Run Code Online (Sandbox Code Playgroud)

但是对于我评论过的行,我现在得到了这个错误:

Property 'content'
 does not exist on type 'Object'.
Run Code Online (Sandbox Code Playgroud)

但是,如果我console.log(sidebar)得到以下内容:

{_id: "59dde326c7590a27a033fdec", content: "<h1>sidebar here</h1>"}
Run Code Online (Sandbox Code Playgroud)

那么问题是什么?

再一次,Http有效,但HttpClient没有.

Kir*_*kin 22

您可以使用接口,类等指定要返回的类型.例如,您可以使用以下内容:

return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');
Run Code Online (Sandbox Code Playgroud)

作为示例,补充工具栏可能被定义为:

interface Sidebar {
    _id: string;
    content: string;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Typechecking Angular文档的回复:

... TypeScript会正确地抱怨从HTTP返回的Object没有结果属性.那是因为当HttpClient将JSON响应解析为Object时,它不知道该对象是什么形状.


Fat*_*med 17

替代方案:

this.sidebarService.getSidebar().subscribe(sidebar => {
 this.sidebar = sidebar["content"];
});
Run Code Online (Sandbox Code Playgroud)

将返回HttpClient中的值,HttpClient会自动解析对象的JSON响应,并且该对象的形状未知,这就是Typescript显示此错误的原因


May*_*ngh 13

您可以为变量(侧边栏)分配一个接口,以明确说明它将获取或分配给它的所以它不会抛出编译时错误.

this.sidebarService.getSidebar().subscribe((sidebar: any) => {
                        this.sidebar = sidebar.content; 
                    });
Run Code Online (Sandbox Code Playgroud)


Cen*_*MUR 5

你可以用type这样的 <any>

如果执行此操作,则不会收到该错误

this.http.get<any>('http://localhost:3000/sidebar/edit-sidebar');
Run Code Online (Sandbox Code Playgroud)