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.
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"];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With