I am currently facing an issue with the code snippet provided below. The constructor is utilizing router methods to retrieve the previous route and store a variable in it. However, when I call `ngOnInit()`, which then triggers another method that compares the saved variable from the constructor with values from a service, the stored variable always seems to be undefined at this point.
Interestingly, within the constructor, the value of `this.selBoard` is set to 40. Yet, whenever I print out the value using `console.log(this.selBoard);`, it constantly shows up as undefined.
I have confirmed that there are no syntax errors present in the async function calls. The fact that the correct value (40) is logged within the constructor indicates that the variable should not be undefined inside `getRouterDetails()`.
//...
selBoard : number;
selectedBoard : Board= new Board();
constructor(private router: Router) {
this.router.events.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
.subscribe((events: RoutesRecognized[]) => {
var url = events[0].urlAfterRedirects;
var urlIndex = url.indexOf('boardId=');
var boardId = url.substring(urlIndex+8, urlIndex+10);
this.selBoard = Number(boardId);
console.log('selBoard --- '+this.selBoard);
});
ngOnInit(): void {
//..
if (this.loggedInUser.isAdmin) {
this.loadBoardsList();}
..//
}
loadBoardsList() {
this._boardService.loadBoards().subscribe( posts => {
this.data = posts;
console.log('loadBoardsList', this.data);
},
error => {
console.log('loadBoardsList - error',error);
// this._errorService.handleError(error);
this._messageService.add({severity:'error', summary:'Error Message', detail:error.error+' - '+error.message, sticky: true});
},
() => {
this.boardsList = this.data.boardLi;
this.getRouterDetails();
console.log(this.selectedBoard);
});
}
getRouterDetails() {
for (let i = 0; i < this.boardsList.length; i++) {
console.log(this.boardsList[i].id);
console.log(this.selBoard);
if (this.boardsList[i].id == this.selBoard) {
console.log('Which one selected ---'+this.selBoard);
this.selectedBoard = this.boardsList[i];
}
}
}
If anyone has any suggestions or insights on how to approach this issue, please feel free to share. Thank you!