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; // this does not work Now
                    });

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

Property 'content'
 does not exist on type 'Object'.

但是,如果我console.log(侧边栏)我得到以下内容

{_id: "59dde326c7590a27a033fdec",content: "<h1>sidebar here</h1>"}

那么问题是什么?

Http再次起作用,但HttpClient却没有.

您可以使用接口,类等指定要返回的类型.例如,您可以使用以下内容
return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');

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

interface Sidebar {
    _id: string;
    content: string;
}

有关详细信息,请参阅Angular文档中的Typechecking the response

…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.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...