andrey.shedko
andrey.shedko

Reputation: 3238

Angular2 route throw 404 error

I have quite simple navigation in my Angular2 application, so I surprised why I'm getting error 404.As you can see ItemDetails component that responsible for showing item details are injected. Here is main.ts configuration:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule}  from '@angular/forms'
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {App} from './app';
import {HttpModule}  from '@angular/http';
import {MdlModule} from 'angular2-mdl';
import {RouterModule, Routes}   from '@angular/router';
import {Main} from './app/containers';
import {DataService} from './app/services/data-service';
import {
    AppBar,
    ShortSearch,
    Authorization,
    Search,
    CollapseOnClick,
    ItemsList,
    ItemDetails,
    NavigationBar,
    SortByPricePipe,
    PageNotFound
} from './app/components';

const appRoutes: Routes = [
    { path: '', component: ItemsList },
    { path: '**', component: PageNotFound },
    { path: 'search', component: Search },
    { path: 'item/:id', component: ItemDetails }
];

@NgModule({
    declarations: [
        App,
        Main,
        AppBar,
        ShortSearch,
        Authorization,
        Search,
        CollapseOnClick,
        ItemsList,
        ItemDetails,
        NavigationBar,
        SortByPricePipe,
        PageNotFound
    ],
    imports: [BrowserModule,
        FormsModule,
        HttpModule,
        MdlModule,
        RouterModule.forRoot(appRoutes)
    ],
    bootstrap: [App],
    providers: [DataService]
})
export class AppModule {
}

platformBrowserDynamic().bootstrapModule(AppModule);

Upvotes: 1

Views: 767

Answers (1)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37403

always make '**' your last path in the your appRoutes array and '' before it:

const appRoutes: Routes = [
    { path: 'search', component: Search },
    { path: 'item/:id', component: ItemDetails }
    { path: '', component: ItemsList },
    { path: '**', component: PageNotFound },
];

Upvotes: 2

Related Questions