Angular 4 - Http 到 HttpClient - 类型 Object 上不存在属性“someproperty" [英] Angular 4 - Http to HttpClient - property 'someproperty' does not exist on type Object

查看:28
本文介绍了Angular 4 - Http 到 HttpClient - 类型 Object 上不存在属性“someproperty"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

...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 - 类型 Object 上不存在属性“someproperty"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆