0

I'm setting up a Angular Service to retrieve dummy data from an API and push the 3 first elements to a TypeScript Class property, but I'm getting this error: Uncaught (in promise): TypeError: Cannot read property 'group' of undefined

Making use of fetch method and a for loop, I'm trying to push the 3 first returned objects to a declared, empty property within the class, however, I get an error when trying to push the data. I'm not able to see the cause of the problem.

export class DishService {

  group = [];

  constructor() {     
  }

  fetchIt() {
    fetch('https://jsonplaceholder.typicode.com/todos')
    .then(response => response.json())
    .then(function(json){
      for(var i = 0; i<3; i++){
        console.log(json[i])
        this.group.push(json[i])
      }
    })
  }
}
pizzaisdavid
  • 455
  • 3
  • 13
Julio Rodríguez
  • 447
  • 1
  • 8
  • 23
  • in the second `then` block, try changing `function(json){` to `(json) => {`, if that fixes it I'll write up an answer. – pizzaisdavid Jan 07 '19 at 23:51
  • How and when are you calling `fetchIt` method? – veben Jan 08 '19 at 00:12
  • @pizzaisdavid, That worked like a charm, I investigated and found out that fat arrows does not have a context and that's why using it, the "this" takes the context of the class... Thanks for the hint buddy. – Julio Rodríguez Jan 08 '19 at 03:03
  • @veben , I'm injecting this "super noob tiny" service into another component, and I'm calling it within it's `ngOnInit()` method – Julio Rodríguez Jan 08 '19 at 03:10

1 Answers1

1

The error says that "this" is undefined, that is because "this" refers to the object which contains the method being invoked, in your case - "then", and not the DishService class.

You can use arrow function as suggested here: Why is 'this' undefined inside class method when using promises?

noam steiner
  • 4,034
  • 3
  • 27
  • 42