1

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.

7
  • 2
    Array is also an Object Commented Mar 19, 2019 at 19:10
  • Try console.log(typeof []);: you'll get object too. An array is an object. Commented Mar 19, 2019 at 19:11
  • So how can i use a method like splice on the object returned? Commented Mar 19, 2019 at 19:14
  • @Fishlex : sure, (rsp: any[]) Commented Mar 19, 2019 at 19:14
  • 1
    Exactly what i was looking for. Thank you Pranav. I think i should focus more on typescript. Commented Mar 19, 2019 at 19:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.