How can I access data inside ngOnInit in Angular?

228 Views Asked by At

I am using subscribe to get data inside ngOnInit. I want to do some operation based on the value received from it. But when I am trying to access it in ngOnInit, it is undefined.

My class :

export class UserPropertiesTO {
  verifierRoles: string[];
  rolesWhichCannotBeOwners: string[];
  showcaseRoles: string[];
  unManageRoles: string[];
}

My component.ts file

export class UserPageComponent implements OnInit {

  userPropertiesTO: UserPropertiesTO;
 
  constructor(private userService: UserService) {
  }
  
  init(){
    this.userPropertiesTO = new UserPropertiesTO();
 
    this.onRoleLoad(() => {
      this.userService.retrieveUserProperties().subscribe(data => {
        this.userPropertiesTO = data;
      })

      if(this.userPropertiesTO.showcaseRoles.includes(someValue) {   //it is showing undefined here
        // want to do some operation here
      }
    }); 
      
 }

  ngOnInit(): void {
    super.ngOnInit();
    this.init();
  }

And following is my retrieveUserProperties method in service file

 retrieveUserProperties(): Observable<UserPropertiesTO> {
    return this.http.get<UserPropertiesTO>('/user/UserProperties');
  }
1

There are 1 best solutions below

0
Yong Shun On BEST ANSWER

Observable is asynchronous. Based on your current code, the if statement will be executed synchronously without waiting for the observable to be returned. Thus that's why the userPropertiesTO.showcaseRoles is undefined.

Move the if statement within the subscribe function so that it will be executed when the observable/response is returned.

this.userService.retrieveUserProperties().subscribe(data => {
  this.userPropertiesTO = data;

  if (this.userPropertiesTO.showcaseRoles.includes(someValue) {
    // want to do some operation here
  }
})