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');
}
Observable is asynchronous. Based on your current code, the
ifstatement will be executed synchronously without waiting for the observable to be returned. Thus that's why theuserPropertiesTO.showcaseRolesisundefined.Move the
ifstatement within thesubscribefunction so that it will be executed when the observable/response is returned.