During the initialization of a component I want to retrieve some user information. Now, with the Angular strict mode, I'm not sure where to load this data?
I can think of 3 options. But which is the correct one? Or is there another possibility?
#1 in this option the service method will be called directly on initialization of the userInfo.
export class NavComponent implements OnInit {
public userInfo$: Observable<LoggedInUser> = this.sessionService.getUserInformation();
constructor(private sessionService: SessionService) {}
ngOnInit(): void {}
}
#2 In my opinion it will be better to source this into the constructor like so:
export class NavComponent implements OnInit {
public isMobileMenuCollapsed = true;
public userInfo$: Observable<LoggedInUser>;
constructor(private sessionService: SessionService) {
this.userInfo$ = this.sessionService.getUserInformation();
}
ngOnInit(): void {}
}
#3 in the ngOnInit-method instead of the constructor. But for this solution I need the Definite Assignment Assertion as well:
export class NavComponent implements OnInit {
public isMobileMenuCollapsed = true;
public userInfo$!: Observable<LoggedInUser>;
constructor(private sessionService: SessionService) {
}
ngOnInit(): void {
this.userInfo$ = this.sessionService.getUserInformation();
}
}
Which of this possibilties should I use in my code?