When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data.
I have considered 3 options. But which one is the most appropriate? Is there another alternative?
#1 This option involves calling the service method 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 I believe it would be more beneficial to initialize this in the constructor:
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 rather than the constructor. However, for this solution, I also require the Definite Assignment Assertion:
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 these options should I implement in my code?