簡體   English   中英

Angular 2 路由器評估多個路由參數

[英]Angular 2 router evaluating multiple route parameters

在我的應用程序中,我有多個參數的路由,例如

http://localhost:3000/department/6/employee/45/sales?from=20160921&to=20160928

我如何最好地評估這些參數? 我可以訂閱ActivatedRoute paramsqueryParams

this.route.params.subscribe(params => ...load data for params);
this.route.queryParams.subscribe(queryParams=> ...load data for queryParams);

但是,這當然會觸發加載兩次。 另外,我總是需要這兩條信息,例如上面的例子中的salesfrom / to

所以上面的代碼變成

this.route.params.subscribe(params => {
    let queryParams = this.route.snapshot.queryParams;
    ...load data for params/queryParams
}

this.route.queryParams.subscribe(queryParams => {
    let params = this.route.snapshot.params;
    ...load data for params/queryParams
}

而且我還沒有解決兩次觸發加載的問題。

更糟糕的是,我還需要弄清楚我的ActivatedRoute需要上升多少級,所以看到它並不罕見

this.route.parent.parent.parent.params.subscribe(...)

啊。 無論如何,這會因延遲加載的組件而崩潰。 無論如何,只是為了檢索少量路由參數需要大量樣板代碼。

我這樣做錯了嗎? 有沒有推薦的方法來解決這個問題?

你可以試試下面,

paramSubscription = Observable.forkJoin(
  this.route.params,
  this.route.queryParams,
  this.route.parent.parent.parent.params
).subscribe(res => {
   this.combinedParams = { params :res[0], queryParams :res[1], ancestorParam : res[2] };
   // Load data
 });

// unsubscribe from the subscription
ngOnDestroy = () => {
    this.paramSubscription.unsubscribe();
}

請注意,我還沒有測試過這段代碼。

希望這可以幫助!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM