【问题标题】:Combine route and query parameters in Angular在 Angular 中组合路由和查询参数
【发布时间】:2017-11-08 09:45:42
【问题描述】:

在 Angular 中,我必须处理格式为

的路由
/sections/{id}?filter={filter}

即我有一个路由参数(id)和一个查询参数(filter)。这两个参数都是可选的,所以所有这些路由都是有效的并且被监听

/sections/{id}?filter={filter}
/sections?filter={filter}
/sections/{id}
/sections

在处理路由时,我需要调用一个可能很昂贵的服务,并提供给定的参数。我可以同时订阅路由的 paramsqueryParams,但我只想在每次 url 更改时调用一次服务,避免任何不需要的调用。

问题是当从/sections/1?filter=active 移动到/sections/2 时,两个可观察对象都会触发,我无法控制哪个会先触发。另一方面,当从/sections/1?filter=active 移动到/sections/1,或从/sections/1?filter=active 移动到/sections/2?filter=active 时,只会触发一个。

有什么理智的方法可以知道最后一次订阅何时触发,这样我就可以避免发送不需要的服务器调用?


目前的测试代码如下所示:

constructor(private activeRoute: ActivatedRoute, private dataService: dataService) {

    this.activeRoute.paramMap.subscribe((params: ParamMap) => {
        console.log("triggering route params subscription");
        this.section = params.get("id");
        this.dataService.runSlowQuery(this.section, this.filter);
    });

    this.activeRoute.queryParamMap.subscribe((queryParams: ParamMap) => {
        console.log("triggering query params subscription");
        this.filter = queryParams.get("filter");
        this.dataService.runSlowQuery(this.section, this.filter);
    });
}

【问题讨论】:

    标签: angular observable angular-router


    【解决方案1】:

    1。订阅路由器事件

    您可以订阅路由器events。这将使您能够访问UrlTree 对象,从而提供更大的灵活性。

    import { Router, UrlTree, NavigationEnd } from '@angular/router';
    
    ...
    
    constructor(private router: Router) {}
    
    ...
    
    let navigation = this.router.events
       .filter(navigation => navigation instanceof NavigationEnd)
       .map((navigation) => {
         let urlTree = this.router.parseUrl(navigation['url']);
         let queryParams = urlTree.queryParams;
         let segments = urlTree.root.children['primary'] ? urlTree.root.children['primary'].segments : null;
         return { queryParams: queryParams, segments: segments }
       });
    
    navigation.subscribe((navigation) => { ... });
    

    2。使用combineLatest

    let params = this.activeRoute.paramMap;
    let queryParams = this.activeRoute.queryParamMap;
    let navigation = Observable
       .combineLatest(params, queryParams, (params, queryParams) => ({ params, queryParams }));
    
    navigation.subscribe((navigation) => { ... });
    

    【讨论】:

    • 谢谢你的答案,但这有点迂回。
    • 编辑问题
    • 添加了另一个解决方案。
    • 我想如果我 combineLatest params、queryParams 和 NavigationEnd,我将能够确定导航结束的时间,并且可以轻松访问数据。
    • combineLatest 应该会为您解决这个问题。不需要 NavigationEnd。
    猜你喜欢
    • 2017-04-03
    • 2016-09-21
    • 1970-01-01
    • 2017-07-07
    • 2012-11-26
    • 1970-01-01
    • 2018-11-05
    • 2018-12-28
    • 2021-08-23
    相关资源
    最近更新 更多