3

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);
  }
}

2 Answers 2

12

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

5

Maybe the resolve function is running before the queryParams are populated in the url. Try doing it in an Rxjs way.

import { filter, map, switchMap, tap } from 'rxjs/operators';
...
export class UserResolver implements Resolve<User[]> {
  constructor(private userService: UserService, private route: ActivatedRoute) { }

  resolve(): Observable<User[]> {
    return this.route.queryParams.pipe(
      tap(params => console.log(`Params: ${params}`)),
      // wait until params has user in it
      filter(params => !!params['user']),
      tap(params => console.log('after filter')),
      // extract the value of the user param
      map(params => params['user']),
      // switch to a new observable stream once we know the searchTerm
      switchMap(searchTerm => this.userService.getUsers(searchTerm)),
    );
  }
}

Edit

Use the tap operator to debug the stream. See what the log is and make sure console.log(Params: ${params}) has the user params.

Edit2

Try

this.router.navigateByUrl(`/search-result?user=${searchTerm}`);

, I am thinking there is something wrong with how you navigate.

Edit 3

I am thinking queryParams can only be read when the component itself loads and not at the run time of the route resolvers because it is saying, I need to go to the route of search-result, give me the data before I go to search-result and it is independent of the queryParams. To fix this, I followed this guide (https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html).

1.) In app-routing-module.ts, change the registration of the path to:

{ path: 'search-result/:user', component: UserListComponent, resolve: { users: UserResolver } },

Now the user will be the parameter we are after in the URL.

2.) In search.component.ts, change search to:

search(searchTerm: string) {
    if (searchTerm) {
      this.router.navigate([`search-result/${searchTerm}`]);
    }
  }

3.) In user-resolver.service.ts, change it to this:

@Injectable({
  providedIn: 'root'
})

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

  resolve(route: ActivatedRouteSnapshot): Observable<User[]> {
    const searchTerm: string = route.paramMap.get('user');

    return this.userService.getUsers(searchTerm);
  }
}

I when console logging searchTerm, it is the accurate value. Thanks for providing the StackBlitz, it helped you and me.

7 Comments

Thank you, but apparently the page no longer navigates from the Search component, any suggestions?
I have edited the solution, you will have to debug with the tap operator.
log from first tap operator "Params: [object Object]", but doesn't proceed or navigate to the UserList component
Yea, the filter is stopping it from proceeding any further. Try the new edit I suggested.
Still the same sad Emoji
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.