I am stuck with passing object to the resolver in Angular 9/10. Any help will be deeply appreciated.
I have a page SearchUser.component.ts
from where I am navigating to another page UserInfo.component.ts
. I am trying to pass the object in the resolver, which can execute my service with the user object model.
A) SearchUser.component.ts
viewUser() {
/*Data to be posted before the User info page is displayed*/
let data = {
"UserId": 1 "UserName": "David",
"Department": "Physics"
}
/*STEP_1 Payload on the router*/
const navigationExtra: NavigationExtras = { state: data };
this.router.navigate(['Default/ApplicationDisplay', navigationExtra]);
}
B) resolve-user.guards.ts
( Here at Step 2 I am expecting the data which can be posted on the API) . But its showing null value.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Resolve, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { MyUserService } from '../services/my-user.service';
@Injectable({
providedIn: 'root'
})
export class ResolveApplicationDetailsGuard implements Resolve < userList > {
private postData: any;
constructor(private _myUserService: MyUserService, private router: Router) {
this.postData = router.getCurrentNavigation().extras.state; //STEP_2
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < userList > | Promise < userList > | userList {
return this._myUserService.GetUsersData(this.postData);
}
}
UserInfo.component.ts
getUserInfo() {
//STEP_3
this.activatedRoute.snapshot.data['userList'];
}
app-routing.ts
path: 'UserInfo',
component: UserInfoComponent,
resolve: {
userList: UserInfoGuard
}
Appreciate if anyone can point me the right direction as certainly I am missing something.
Am I reading it right -
let data
is not in the same scope (it is insideviewUser
method) asconst navigationExtra
?If
navigationExtra
is outsie theviewUser
method, you can not do this{state:data}
, because data is not accessible in this scope. You have to assigndata
to a component's own property and then declare constnavigationExtra
like this: