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

标签 angular typescript

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

最佳答案

您可以使用接口(interface)、类等指定返回的类型。例如,您可以使用如下所示的内容:

return this.http.get<Sidebar>('http://localhost:3000/sidebar/edit-sidebar');

例如,侧边栏可能定义为:

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

参见Typechecking the response从 Angular 文档获取更多信息:

...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 - 对象类型上不存在属性 'someproperty',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47484875/

相关文章:

css - 使用 CalendarModule 溢出 PrimeNG DialogModule

angular - ngFor 不工作

typescript - 类型 'By' 的参数不可分配给类型 'ProtractorBy | WebElement' 的参数

javascript - TypeScript -> 用于浏览器的 JavaScript : exports/require statements

javascript - Renderer2 错误 - id 与任何元素都不匹配

html - 如何在调整窗口大小(缩小)时将工具栏转换为侧边导航栏?

c# - 在 Angular 和 .Net Core API 中显示自定义服务器端错误消息

javascript - HTML5 : Attributes are not recognized after being added with JS/Jquery

javascript - 禁用按钮时 '@typescript-eslint/no-non-null-assertion' 的用途

typescript - 将 string[] 字面量转换为 string 类型字面量