0

my code

this.service.getName().subscribe((success: any) => {
  if (success) {
    for (let i = 0; i < success[i].length; i++) {
      if (success[i].data.empid== data) {
        this.dataList.push(success[i].name);
      }
    }
  }
});

Unable to access the this.dataList outside subscribe

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
sankar
  • 21
  • 1
  • 5
  • Most likely relevant: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – VLAZ Mar 16 '21 at 11:15
  • You can't. Any statements that directly depend on `this.dataList` must be inside the subscription. In other words, subscribe where it's response is required. There are ways to cache a result from an observable though. Try googling it. At the end, the data must and _mostly_ will remain asynchronous and reactive. – ruth Mar 16 '21 at 11:18
  • Do you display this field in html ? Or do you try to read the value immediately after calling `this.service.getName()` – Arnaud Denoyelle Mar 16 '21 at 11:19
  • @ArnaudDenoyelle, need a value immediately after calling the service – sankar Mar 16 '21 at 11:20
  • 1
    You should simply put the code inside the subscribe, is there a problem with doing that? If so, you should expand on your question. The question as it looks now is identical to countless of other questions on this website – ShamPooSham Mar 16 '21 at 12:11

1 Answers1

4

You try to read this.dataList immediately after the call to this.service.getName() but you have an ordering problem. Consider the following piece of code :

this.service.getName().subscribe(() => console.log('A'));
console.log('B')

This will display B A because the call to this.service.getName() is asynchronous.

What happens is :

  • Call this.service.getName()
  • Call console.log('B')
  • Browser get the response from this.service.getName() and executes () => console.log('A')

Because of that, you try to read this.dataList too soon, when it is still empty or undefined. You should read its value inside the callback :

this.service.getName().subscribe((success: any) => {
  if (success) {
    for (let i = 0; i < success[i].length; i++) {
      if (success[i].data.empid== data) {
        this.dataList.push(success[i].name);
      }
    }

    // Here, you can safely read this.dataList
    [...]
  }
});
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148