Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - Http to HttpClient - property 'someproperty' does not exist on type Object

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.

like image 672
Vojislav Kovacevic Avatar asked Nov 09 '17 12:11

Vojislav Kovacevic


2 Answers

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.

like image 66
Kirk Larkin Avatar answered Nov 12 '22 07:11

Kirk Larkin


HttpClient parse automatically the JSON response to an Object and the shape of that object is not known, that's why Typescript show this error

alternative solution, using bracket notation:

this.sidebarService.getSidebar().subscribe(sidebar => {
 this.sidebar = sidebar["content"];
});
like image 19
Fateh Mohamed Avatar answered Nov 12 '22 08:11

Fateh Mohamed