将管道与skipWhile结合使用时,如何获取路由器参数?

时间:2019-10-02 09:53:08

标签: angular router angular-activatedroute

我有一个动态的BreadCrumb导航,需要从URL获取参数。为此,我正在执行以下代码:

function getdata(a,b, callback)
{
    var somevalue = '';
    request(req,function(){
        //somecode
        //assign value to 'somevalue'
        callback(someValue);
    });

}
var value = '';
function abc()
{
    getdata(a,b , function(data) { 
        value = data:
        if (value != 'x)
            abc();
    });
}
abc();

但是它始终是空的,并且我从来没有将参数传递给Observable。当我使用 const userId = this.activatedRoute.params .pipe(skipWhile((params: Params) => Number.isNaN(+params['userId']))); const getAppUserId = userId.pipe( switchMap((params: Params) => { return +params['userId'] ? this.myAppService.getApplicationUser(+params['userId']) : of('') })) 时,它可以正常工作,但我不想采用 queryParams 的概念。 知道我哪里出错了吗?

3 个答案:

答案 0 :(得分:0)

我曾经做过一个自动面包屑生成器,该构建器仅依赖您路线中的静态数据。我设法找到了它,因此,如果有帮助,您可以开始这里:

export class RouteBreadcrumbsComponent {

  breadcrumbs = [];

  constructor(
    private router: Router,
  ) {
    let buffer = [];

    /* 
       Listen for router events in reverse order (to get all events).
       From the snapshots, return its path and its breadcrumb.
    */
    this.router.events.pipe(
      filter(event => event instanceof ActivationEnd),
      map((event: ActivationEnd) => [
        event.snapshot.data && event.snapshot.data.crumb || undefined,
        this.determineCorrectPath(event.snapshot),
      ]),
      filter(([crumb, url]) => !!crumb),
    ).subscribe(([crumb, url]) => buffer.push({ crumb, url }));

    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe(event => {
      this.breadcrumbs = buffer.reverse();
      buffer = [];
    });
  }

  determineCorrectPath(snapshot: ActivatedRouteSnapshot) {
    const path = snapshot.routeConfig.path;
    const params = snapshot.params;

    // Path = route with a param, so get the param
    if (path.startsWith(':'))
      return params[path.replace(':', '')];
    // Path = '' = route group or root route of a lazy loaded module, so take the parent path
    else if (!path)
      return snapshot.parent.routeConfig.path;
    // Path can be used as is
    else
      return path;
  }

  buildRoutingArray(crumbIndex: number) {
    return this.breadcrumbs
      .slice(0, crumbIndex + 1)
      .map(crumb => crumb.url)
      .join('/');
  }
}

您要做的就是为每条路线提供一个data: { crumb: 'Your component crumb' },它应该可以工作。

答案 1 :(得分:0)

第一期:

Number.isNaN(+params['userId'])

返回字符串,而不是数字。

第二个问题:

const getAppUserId = userId.pipe(
  switchMap((params: Params) => {

您不是从可观察的对象中获取参数,而是从用户ID(实际上是布尔值)中获取参数。

如果您希望“从/通过可观察的获取参数ID,然后将其用于:带有switchMap的getAppUserId,以使用我从snapshot.params获得的参数ID进行HTTP调用”

那么正确的代码应该是

this.activatedRoute.params.pipe(
  map(params => params.id),
  switchMap(userId => this.myAppService.getApplicationUser(userId)
);

您不应该测试ID的有效性:URL是字符串,您不能信任用户。只需发出请求,如果ID不匹配任何内容,则您的API将不会返回任何内容。让API对ID(而不是您的客户端)进行所有控制。

答案 2 :(得分:0)

问题已解决。很简单...解决方法是从 route.snapshot 捕获参数。

this.router.events
        .pipe(filter(event => event instanceof NavigationEnd))
        .pipe(map(() => {return this.activatedRoute;}))
        .pipe(
            map((route) => {
                while (route.firstChild) {route = route.firstChild;}
                return route;
            })
        ).subscribe(route => {
             console.log(`param: ${route.snapshot.params['id']}`);
             ...
             ...
        });