Lakhvir Singh
Lakhvir Singh

Reputation: 672

How to hold the life cycle of component after constructor till the function in constructor was not completed?

I am working on angular2 application.

I have a component which will display my menu. In this component I have a list of menu items (array) and in constructor I am calling an api to get permissions of menu items in true/false. In HTML file looping through menuList array to print it and compering every menuList item with permissions object. If there is permission then it will display it otherwise no.

I am getting an error because api takes time to return data but html was build before it returns response. That's why I want first to get response of api after that initialisation of component.

Upvotes: 0

Views: 58

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105497

In HTML file looping through menuList array to print it I'm assuming you're using ngFor and construction like this to show the items:

<menu-item *ngFor="let item of menuItems"..>

The best approach in this case would be not fill menuItems with values until you get the response from the server. Something along these lines:

export class MenuComponent {
  menuItems = [];
  constructor(s: BackEndService) {
  }

  ngOnInit() {
       s.getPermissions().toPromise().then((permissions)=>{
          permissions.forEach(()=>{
             // some calculations
             menuItems.push(item);
          })
       })
  }
}

Upvotes: 1

Related Questions