![](/img/trans.png)
[英]Angular 9 how to handle ampersand(&) inside activated route param field
[英]Angular 4 - Activated Route with param
我有一個列表頁面和一個詳細信息頁面。 從列表頁面中選擇項目將路由到詳細信息頁面。
路由模塊:
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});
}
問題:選擇項目會轉到此URL: 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
我究竟做錯了什么?
我認為問題是我在列表頁面的html上有這個:
<a href="item/{{item.id}}">{{item.id}}</a>
我改成了:
<a [routerLink]="['/item', item.id]">{{item.id}}</a>
並從組件中刪除它:
goToDetail(item) {
this.router.navigate(['item'], {id: item.id});
}
這有效!
您的路線定義明確。 但是您有3種基本方法可以重定向: href , routerLink和router.navigate 。
這個是在 Angular控制之外 。 在項目 列表組件的模板( html文件 )中,您可以添加簡單的錨點html標記:
<a href="...an static url..">Text of this link</a>
但是,因為這種方式是在Angular控制之外,你應該使用這個解決方案可能用於外部永久性靜態URL。 像Google Page,Facebook Page等。
因此,在這種情況下 :用戶與您的DOM交互,您的DOM將觸發一個事件,使您的瀏覽器重定向您。
此解決方案要求以某種方式將RouterModule導入到實際的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 屬性作為輸入 (Between []
)和路徑段數組,其中包含按順序排列的每個段:
<... [routerLink]="['/model', 'item', item.id]">...</...>
將item作為模板上的可訪問對象 (類組件內的公共變量或模板中聲明的變量,如使用*ngFor="let item of items"
),其id為屬性。
注意:您可以使用[routerLink]="['/model/item', item.id]"
簡化該鏈接,因為/model/item
在url中是靜態的。
因此,在這種情況下 :用戶與您的DOM交互,您的DOM將調用RouterModule ,最后一個將結束在您的路由中尋找匹配,使Angular重定向您。
該解決方案的方法,另外 需要 進口,注入要處理的路線(ItemListComponent在這種情況下- ItemList.component.ts文件),該組件的路由器 。
要導入路由器,請添加以下內容:
import { Router } from '@angular/router';
注入它; 將它添加到構造函數 :
constructor(private router: Router) {}
然后,添加要在類中處理重定向的方法 ,如您添加的方法:
goToDetail(item) {
this.router.navigate(['/item', item.id]);
}
最后,您需要在模板中添加一個可以調用您的函數的事件。 例如:
<... (click)="goToDetail(item)">...</...>
因此,在這種情況下 :用戶與您的DOM交互,您的DOM會觸發一個事件,該事件將在您的類上觸發一個方法,該方法將調用該方法從Router類導航 ,這將最終查找您的路由中的匹配,使Angular成為重定向你。
Angular可以使用三種不同類型的參數: required
, optional
和query
參數。
要像在示例中一樣管理詳細信息頁面上的ID,您很可能希望使用required
參數。
您對required
參數的配置是正確的。
但是導航到參數是使用optional
參數語法。
將其更改為:
this.router.navigate(['item', item.id]);
需要在數組中定義Required
參數。
有關三種不同類型參數的詳細討論,請查看此Pluralsight課程: https ://app.pluralsight.com/library/courses/angular-routing
請試試這個:
this.router.navigate([ '項目' + item.id]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.