我正在學習Angular 2,並在設置兒童路線時受阻。角度2:兒童路線不起作用
我想構建簡單的ToDo應用程序,並且無法設置添加新項目的路線。
這就是我想要得到和'待辦事項/添加'鏈接不工作,並繼續給我404錯誤。
實例:
- 本地主機/待辦事項
- 本地主機/ TODO /添加
我在app.module.ts加入todo.module.ts。
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from "./home/home.component";
import { AppComponent } from "./app.component";
import { PageNotFoundComponent } from "./not-found.component";
import { TodoListComponent } from "./todo/todo-list.component";
import { TodoModule } from "./todo/todo.module";
@NgModule({
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{ path: 'todo', component: TodoListComponent },
{ path: '**', component: PageNotFoundComponent }
],
TodoModule)
],
declarations: [
AppComponent,
HomeComponent,
TodoListComponent,
PageNotFoundComponent
],
bootstrap: [AppComponent],
})
export class AppModule { }
而且在todo.module.ts爲待辦事項建立子路由/加
todo.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TodoListComponent } from './todo-list.component';
import { TodoAddComponent } from './todo-add.component';
@NgModule({
imports: [
RouterModule.forChild([
{ path: 'todo', component: TodoListComponent },
{ path: 'todo/add', component: TodoAddComponent }
// tested these routes and not working too
//{ path: 'add', component: TodoAddComponent }
//{ path: 'todo/:id', component: TodoAddComponent }
])
],
declarations: [
TodoAddComponent,
TodoListComponent
],
providers: [
]
})
export class TodoModule { }
我測試我在互聯網上發現的3種可能的方式,他們都給我404錯誤(重定向到PageNotFoundComponent)
<h1>Todo List</h1>
<a [routerLink]="['/todo/add']">Add New Item with /</a><br />
<a [routerLink]="['/todo', 'add']">Add New Item</a><br />
<a [routerLink]="['add']">Add New Item</a>
它們呈現爲/ todo/add,/ todo/add,/ add,但所有這些命令都遇到了404錯誤。
難道你們,請幫我理清這個問題?
有時,我對自己(或者可能是Angular2)感到非常沮喪,無法理解爲什麼學習/做簡單的事情非常困難。
你救了我。非常感謝。主要問題是我在ForRoot支架中意外添加了TodoModule。您的解釋讓我清楚瞭解Angular2中的Routing如何工作。 – TTCG
附加問題...如果我直接在地址欄中鍵入'localhost/todo'或'localhost/home',它可以工作......但如果我輸入'localhost/todo/add',則無法加載所有庫.js文件(shin.min,zone,reflect等),併爲所有這些庫提供404。 – TTCG
您使用什麼代碼加載庫?你在使用SystemJS還是Webpack? – AngularChef