Reputation: 46
Just started with angular(version 7). I try to get a response from json-placeholder, an array of todos. That should return an array but when i console.log(typeof rsp) it shows an object.
Observable:
url: string = 'https://jsonplaceholder.typicode.com/todos';
getHomeTodos() {
return this.http.get(this.url);
}
Observer in my component:
ngOnInit() {
this.todosService.getHomeTodos()
.subscribe((rsp) => {
this.homeTodos = rsp;
});
}
Any ideas why the type of rsp is 'Object' but on the json-placeholder it shows it returns an array? Thanks.
Upvotes: 1
Views: 1945
Reputation: 62213
So how can i use a method like splice on the object returned?
I think I see what your question is. You need to specify the return type in get
as well as getHomeTodos
so you add type safety and the IDE can suggest methods/members on the types like splice on an array.
export interface IToDo { /* members here */ }
url: string = 'https://jsonplaceholder.typicode.com/todos';
getHomeTodos():Observable<IToDo[]> {
return this.http.get<IToDo[]>(this.url);
}
homeTodos: IToDo[];
ngOnInit() {
this.todosService.getHomeTodos()
.subscribe((rsp) => {
this.homeTodos = rsp;
});
}
This added type safety and now you can use splice
or other Array prototype members.
Upvotes: 1