roger_that
roger_that

Reputation: 9791

Angular2: Global variable not getting populated after backend api call in ngOnInit

Am trying to populate an object array declared globally inside a component to be used in another function within same component but it's not getting populated.

The browser network tab shows the data in response to the http call but when I try to access the array, it shows undefined.

Here is what am trying:

myArray: MyObject[];
requestPath: string;
one: string;
two: string;
three: string;
four: string;

ngOnInit() {

     this.activatedRoute.queryParams.subscribe((params: Params) => {
     this.one = params['one'];
     this.two = params['two'];
     this.three = params['three'];
     this.four = params['four'];

    this.requestPath = this.getRequestPath(this.one,this.two,this.three,this.four);

    this.http.get(this.requestPath)  //returns a json data
        .map(res => res.json())
        .subscribe(
            data => { this.myArray = data;
        },
        err => console.error(err),
        () => console.log('inside comparator oninit'));
    });
    this.add(this.myArray);
 }

And when I try to access it inside add function:

add(event){
   alert("data is: "+event);
}

I get data is undefined in the alert which means variable is not getting populated with the data fetched.

What is the right way to do this? What's wrong with the code?

Upvotes: 1

Views: 261

Answers (2)

Pardeep Jain
Pardeep Jain

Reputation: 86740

As you are calling an Asynchronous call so you must need to call your method when async call finishes. So you need to call your function inside the subscribe call like this.

Try this-

        .subscribe(
            data => { 
                    this.myArray = data;
                    this.add(this.myArray);
        },

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

You need to call inside the subscribe,

.subscribe(
        data => { this.myArray = data;
        this.add(this.myArray);
 }

Upvotes: 1

Related Questions