0

I have a ngOnInit() method that fills data list at beginning, I am making two different logic according to there is a query param (navigate back to page) or just first opening of the page. But I have a very weird error at these 2 logic.

In below code:

  ngOnInit() {
    this.route.queryParams.subscribe((queryParams: Params) => {
      this.initFilters(queryParams);
      if(this.group) {
        this.getActiveGroups();
        //console.log(this.activeGroupList);
      }
    });
    this.getActiveGroups();
  }

getActiveGroups(): void {
    this.service123.getActiveGroups().subscribe((groupData: Group[]) => {
      this.activeGroupList = groupData;
      //console.log(this.activeGroupList);
    })
  }

Second comment (console.log line) is working good and logging the list data which comes from backend. But first comment is giving error and saying the variable is undefined. They are same variable but why first one is undefined ? I need that list in first commented part also, so I can use it in functions. Or should i define that variable something like static?

How can I achieve it?

abidinberkay
  • 1,857
  • 4
  • 36
  • 68
  • It's undefined because you assign it only after request from server returns at that line of code `this.activeGroupList = groupData;`. Before that it would be undefined. – Amir Arbabian Jan 29 '19 at 15:47
  • Please [edit] your question and include the actual framework you're using. AngularJS is a different framework from Angular. See [AngularJS vs Angular](https://stackoverflow.com/q/34114593/215552). – Heretic Monkey Jan 29 '19 at 15:54

1 Answers1

1

In ngOnInit, you want to use activeGroupList variable before it gets any value since getActiveGroups() method performs an async operation. You can use switchMap from RxJS to combine async calls to get one result like:

ngOnInit() {
    this.route.queryParams.pipe(
      tap((queryParams: Params) => {
          this.initFilters(queryParams);
      }),
      swicthMap(() => {
          return this.service123.getActiveGroups()
      })
    )
    .subscribe((groupData: Group[]) => {
      this.activeGroupList = groupData;
      //console.log(this.activeGroupList);
    })
}

Check this article out for further reading about RxJS map operators: https://netbasal.com/understanding-mergemap-and-switchmap-in-rxjs-13cf9c57c885

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35