I am having difficulties in accessing service data within ActivationEnd router service.
My TS:
export class ListConditionsComponent implements OnInit {
conditions: Condition[];
fCon: string[];
constructor(private _service: ConditionService,
private _router: Router,
private _route: ActivatedRoute) { }
ngOnInit():void {
this._service.getConditions()
.subscribe(data => this.conditions = data);
this._router.events.subscribe(event => {
if(event instanceof NavigationStart) {
}
if(event instanceof ActivationEnd) {
this.fCon = event.snapshot.queryParams["fCon"];
console.log("actiend fCon:" + this.fCon);
console.log("actiend conditions:" + this.conditions);
}
});
}
}
Template:
<ul>
<li *ngFor="let condition of conditions; let i = index">
<label>
<input type="checkbox" value="{{ condition.Id }}" *ngIf="fCon == condition.Id" checked />
<input type="checkbox" value="{{ condition.Id }}" *ngIf="fCon != condition.Id" />
<span>{{ condition.Name }}</span>
</label>
</li>
</ul>
My template being filled without any problem.
But within the TS the console.log says "actiend conditions:undefined".
I can without problem read the fCon variable, but only the conditions variable is being shown as undefined.
I don't know why I cant access the "conditions" within my ActivationEnd event.
Anybody who knows why? thx.
Note:
In case you wonder, why I am accessing queryparams like this is, this is being done in a component which is not being loaded in [router-outlet], therefore I dont have access to the traditional way of accessing queryparams.
AFTER SEVERAL HOURS OF HEADACHE I FOUND THIS WORKS FOR ME
ngOnInit(): void {
this._router.events.subscribe(event => {
if (event instanceof ActivationEnd) {
this.getAllConditions();
}
});
}
async getAllConditions() {
this.conditions = await this._service.getConditions().toPromise();
//from here I can continue as the data will be loaded from hereon
console.log(this.conditions.length); //prints fine the length as the data is loaded
}
thx again to @Kurt Hamiton for pointing about the asynchronous loading and Im sure that your code will be useful for someone also, thats why Im marking yours as answer