0

How can I get a variable outside of a promise block in a component in Angular 6?

For example

    items:string[]=[];

    ngOnInit{

    const url='SOME URL';
    const promise = this.apiService.post(url);

        //Response
        promise.then(response => {
      this.items.push('abc');
      this.items.push('def');
        });

    this.items.forEach(item=>{
     alert(item);
    });

      }

I expect that the application alerts the contents of the items array

freelancer86
  • 511
  • 2
  • 7
  • 20
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Sep 03 '19 at 15:32

2 Answers2

2

When you do

this.items.forEach(item=>{
     alert(item);
    });

the items array is empty.

You need put this code inside

  promise.then(response => {
          this.items.push('abc');
          this.items.push('def');
         this.items.forEach(item=>{
            alert(item);
           });
     });

Or you can use Observables to know when the promise ends and execute the foreach, you need to do something like this:

private subjectItems = new Subject<any>();

ngOnInit{

    this.subjectItems.asObservable().subscribe(o => {
        this.items.forEach(item=>{
         alert(item);
        });
      });

    const url='SOME URL';
    const promise = this.apiService.post(url);

        //Response
        promise.then(response => {
           this.items.push('abc');
           this.items.push('def');

           this.subjectItems.next(this.items)
        });
      }
Miguel Pinto
  • 523
  • 2
  • 8
  • The problem is that I want that the application alerts the items outside the promise block because I want to use the items variable outside the promise block – freelancer86 Sep 03 '19 at 15:35
  • You must have some way of knowing that the promise has resolved. The reason for putting the alert inside the block after `.then` is that you know your promise has resolved at that point. Otherwise, you may execute the `thisitems.forEach(item => alert(item))` at a time when the promise hasn't resolved yet, hence showing nothing as the list is empty. If you are trying to use `this.items` in your template you should be fine as it would update when the value changes anyways. – nicholascm Sep 03 '19 at 15:39
  • @freelancer86 i edit my answer to add other approach, with observables. – Miguel Pinto Sep 03 '19 at 16:09
0

It seems to be an async issue, I mean your alert is being shown before you get data from the service, so an option would be to work with Observables and subscribe. It should wait until getting data before using it.

Also you could try using async/await following this medium article