我需要通过将queryParams通过从搜索组件到userList组件的路由传递来实现“搜索”(例如,/ search-result?user =“ Alfred”)。在加载userList组件之前,我需要使用userList解析器中的queryParams进行API调用,但查询参数始终显示未定义。

搜索组件

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


用户列表解析器

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

最佳答案

可能resolve函数在url中填充queryParams之前正在运行。尝试以Rxjs方式进行操作。

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


编辑

使用抽头运算符调试流。查看日志是什么,并确保console.log( Params:$ {params} )具有用户params。

编辑2

尝试

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


,我认为您的导航方式有问题。

编辑3

我想queryParams仅在组件本身加载时才能读取,而不能在路由解析器的运行时读取,因为这是说,我需要转到search-result的路由,在转到之前先给我数据search-result,它独立于queryParams。要解决此问题,我遵循了本指南(https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html)。

1.)在app-routing-module.ts中,将路径的注册更改为:

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

现在,用户将成为我们在URL中使用的参数。

2.)在search.component.ts中,将search更改为:

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


3.)在user-resolver.service.ts中,将其更改为:

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


我在控制台记录searchTerm时,它是正确的值。感谢您提供StackBlitz,它为您和我提供了帮助。

关于javascript - 如何在Resolver Angular中访问queryParams,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60443768/

10-11 12:27