簡體   English   中英

Angular 2路由解析不同的組件

[英]Angular 2 routes resolve different component

這是我的用例:

當我加載url / product / 123時,我想加載組件ProductComponent

這是我的設置:

RouterModule.forRoot([            
        {
            path: 'product/:productId',
            component: ProductComponent
        },
        {
            path: '**', component: NotFoundComponent
        },
    ]),

現在我添加了一個解析器來檢查該產品ID是否存在,所以我的設置如下所示:

RouterModule.forRoot([            
        {
            path: 'product/:productId',
            component: ProductComponent,
            resolver: {
                productResolver: ProductResolver
            }
        },
        {
            path: '**', component: NotFoundComponent
        },
    ]),

我的解析器通過api調用檢查該productId參數是否存在。 我遇到的問題是,當找不到productId時,我想加載NotFoundComponent而不是重定向到不同的頁面(我不想像angular 2文檔建議那樣更改URL)。

誰知道怎么做? 如果沒有通過解析器找到productId加載NotFoundComponent而不更改url / navigation?

不明白為什么你需要通過路由器設置加載你的組件,我把它放在試圖從服務中獲取它的組件內,然后如果沒有得到結果,則返回切換一些控件的布爾值是否顯示NotFoundComponent。 下面是一些偽代碼:

ngOnInit(){
    if (this.route.snapshot.params && this.route.snapshot.params['id']){
          myService.getTheThingById((success)=>{
                this.isFound = true;
                },(err)=> {
                      this.isFound = false;
          });
}

然后假設您的NotFoundComponent在其中有一個選擇器,如'not-found-component',將其放入模板中,以便調用該服務的組件。

 <not-found-component *ngIf='!isFound'></not-found-component>

我想你要做的就是在導航到NotFoundComponent時跳過位置更改。 我假設你已經將Router注入你的解析器,並且當ID不存在時正在執行類似的操作:

router.navigate(['someUrl']);

或者您可能正在使用navigateByUrl方法。 無論哪種方式,您都可以告訴路由器不要更改URL

router.navigate(['someUrl'], {skipLocationChange: true});

我曾經遇到過這個問題。

我所做的是,在組件中,創建2個其他組件(在您的情況下,您有ProductComponent,NotFoundComponent,另一個要導航到的,讓我們說ArticleComponent)

然后我在主要組件中插入了2個組件:

product.component.html

<app-notFound></app-notFound>
<app-article></app-article>

之后,在ngOnInit ,您會看到參數是否存在。 如果他是,那么你將它記錄在一個屬性中,讓我們說isParam = true

你的模板變成了

<app-notFound *ngIf="!isParam"></app-notFound>
<app-article *ngIf="isParam"></app-article>

它可能不是那里最好的解決方案,但它對我有用!

暫無
暫無

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

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