Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access queryParams in a Resolver Angular

I Need to implement 'search' by passing queryParams through route from the search component to the userList component (example. /search-result?user="Alfred"). Before loading the userList component, i need to make an API call using the queryParams in the userList resolver but the query params keeps showing undefined.

Search Component

search(searchTerm: string) {
    if (searchTerm) {
      this.router.navigate(['search-result'], { queryParams: { user: searchTerm } });
  }
}

UserList Resolver

export class UserResolver implements Resolve<User[]> {
  constructor(private userService: UserService, private route: ActivatedRoute) { }

  resolve(): Observable<User[]> {
    const searchTerm: string = this.route.snapshot.queryParams['user'];
    console.log(searchTerm); //Logs Undefined

    return this.userService.getUsers(searchTerm);
  }
}
like image 745
Ojay Avatar asked Jun 12 '26 05:06

Ojay


1 Answers

On latest versions of Angular you can get the ActivatedRouteSnapshot on the resolver function.

  export class UserResolver implements Resolve<User[]> {
  constructor(private userService: UserService, private route: ActivatedRoute) { }

  resolve(**route: ActivatedRouteSnapshot**): Observable<User[]> {

    **console.log(route.queryParams)**

    return this.userService.getUsers(searchTerm);
  }
}
like image 183
Sergio Inxunxa Avatar answered Jun 14 '26 19:06

Sergio Inxunxa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!