Angular 2 routes allow different components

Here is my use case:

When I load url / product / 123, I want to download the ProductComponent component

This is my setup:

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

Now I have added a recognizer to check if this product identifier exists, so my setup looks like this:

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

My resolver checks if this parameter productId exists through an api call. The problem is that when the productId is not found, I want to load NotFoundComponent and not redirect to another page (I don't want to change the URL, for example, angular 2).

Does anyone know how to do this? if not productId found via loading resolver NotFoundComponent without changing url / navigation?

+4
3

, , , , NotFoundComponent. , Router - , :

router.navigate(['someUrl']);

navigateByUrl. URL:

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

, , , , , , boolean, , 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 *ngIf='!isFound'></not-found-component>
+3

.

What I did, 2 more components were created in the component (in your case, you have ProductComponent, NotFoundComponent and the other you want to go to, say, ArticleComponent)

Then I inserted 2 of the main components:

product.component.html

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

After that, ngOnInityou will see in yours whether there is a parameter. If it is, you write it in the property, say isParam = true.

Your template will become

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

This may not be the best solution, but it worked for me!

0
source

Source: https://habr.com/ru/post/1677531/


All Articles