Reputation: 203
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.
Upvotes: 2
Views: 2440
Reputation: 7640
You can follow these steps:
Send data through routing paths in Angular
I'm not sure but you can try to add data at the end of this line.
this.postData = router.getCurrentNavigation().extras.state.data;
Upvotes: 1
Reputation: 385
Am I reading it right - let data
is not in the same scope (it is inside viewUser
method) as const navigationExtra
?
If navigationExtra
is outsie the viewUser
method, you can not do this {state:data}
, because data is not accessible in this scope. You have to assign data
to a component's own property and then declare const navigationExtra
like this:
navigationExtra: NavigationExtras = {state: this.data};
Upvotes: 2