我有一个列表页面和一个详细信息页面。从列表页面中选择项目将路由到详细信息页面。
路由模块:
const itemRoutes: Routes = [
{ path: 'item', component: ItemListComponent},
{ path: 'item/:id', component: ItemDetailComponent }
];
列表组件:
constructor( private route: ActivatedRoute, private router: Router) {}
goToDetail(item) {
this.router.navigate(['item'], {id: item.id});
}
问题: 选择项目会转到此网址: http://localhost:3000/item/2
但浏览器显示“未找到”错误。
在控制台上,我看到了:
:3000/item/2:1 GET http://localhost:3000/item/2 404 (Not Found)
Navigated to http://localhost:3000/item/2
我做错了什么?
答案 0 :(得分:12)
我认为问题在于我在列表页面的html上有这个:
UITableViewDataSource
我把它改为:
<a href="item/{{item.id}}">{{item.id}}</a>
并将其从组件中删除:
<a [routerLink]="['/item', item.id]">{{item.id}}</a>
这很有用!
答案 1 :(得分:2)
您的路线定义明确。但您有3种基本方法可以重定向: href , routerLink 和 router.navigate 。
这是外部角度控制。在项 列表组件的模板( html文件)中,您可以添加简单的锚点html标记:
<a href="...an static url..">Text of this link</a>
但是,因为这种方式不在Angular控件之外,所以你应该使用这个解决方案来解决外部永久性静态URL问题。像Google Page,Facebook Page等。
因此,在这种情况下:用户与您的DOM互动,您的DOM将触发一个事件,让您的浏览器重定向您。
此解决方案需要 路由器模块以某种方式导入到您的实际ngModule才能工作。在您的主模块(通常 app.module.ts )中执行此操作的最基本方法是您需要添加:
import { RouterModule } from '@angular/router';
并在 @NgModule 装饰器中的imports数组中添加 RouterModule 。
@NgModule({
...,
imports: [
....,
RouterModule,
....
],
...
})
然后在 ItemListComponent 的模板中,您可以引用静态路径,或动态生成 >
要引用静态路径,您只需添加 routerLink 属性并将路径作为值添加:
<... routerLink="/item">If you click this element, you will be redirected to ItemListComponent</...>
注意:<...></...>
表示您使用的标记在页面中呈现时根本不重要。
要引用生成的链接,例如model/item/4
,您需要将 routerLink 属性添加为输入(在[]
之间)和一个路径段数组,其中包含 sequencial 顺序中的每个段:
<... [routerLink]="['/model', 'item', item.id]">...</...>
在模板上 item 一个可访问的对象(类组件中的公共变量 OR 在模板中声明的变量,如使用{{ 1}}) id 作为属性。
注意:您可以使用*ngFor="let item of items"
简化该链接,因为网址中的[routerLink]="['/model/item', item.id]"
静态。
因此,在这种情况下:用户与您的DOM交互,您的DOM将调用 RouterModule ,最后一个将终止在您的路由中寻找匹配使 Angular 重定向你。
此解决方案 导入并注入在您要处理路径的组件中(在这种情况下, ItemListComponent - ItemList.component.ts 文件)。
要导入路由器,请添加:
/model/item
注射它;将其添加到构造函数:
import { Router } from '@angular/router';
然后,添加您想要处理类中重定向的方法,就像您添加的那样:
constructor(private router: Router) {}
最后,您应该在模板中添加一个可以调用您的函数的事件。例如:
goToDetail(item) {
this.router.navigate(['/item', item.id]);
}
因此,在这种情况下:用户与您的DOM进行交互,您的DOM会触发一个事件,该事件将在您的类上触发一个方法,该方法将调用方法导航 路由器类,它将最终查找您的路由中的匹配项,使 Angular 重定向您。
答案 2 :(得分:0)
Angular可以使用三种不同类型的参数:required
,optional
和query
参数。
如您在示例中一样管理详细信息页面上的ID,您很可能希望使用required
参数。
required
参数的配置是否正确。
但您导航到参数的方法是使用optional
参数语法。
将其更改为:
this.router.navigate(['item', item.id]);
需要在数组中定义 Required
个参数。
有关三种不同类型参数的详细讨论,请查看此Pluralsight课程:https://app.pluralsight.com/library/courses/angular-routing
答案 3 :(得分:0)
请尝试这个:
this.router.navigate([ '项目' + item.id]);