[英]Angular Reuse Component in different routes
我有以下路線,其中id是可選參數,因此用戶可以加載信息,或者如果沒有提供id,則可以添加信息。 我希望能夠重用該組件,從而不必重新加載頁面(ngOnInit中的api調用),但是因為它們是兩條單獨的路線,所以angular總是創建一個全新的組件,並調用ngOnInit。
我嘗試過使用兒童,但仍然遇到相同的問題
(這是與Angular 4路由器一起使用的)
const routes: Routes = [
{
path: 'stuff/info',
component: InfoComponent,
},
{
path: 'stuff/info/:id',
component: InfoComponent,
},
]
Angular具有必需,可選和查詢參數。 您定義的“可選”參數不是“可選”,因為Angular已定義了可選參數。 對於“ true”可選參數,您無需將其定義為路由配置的一部分。 因此,您可以像這樣僅用stuff/info
來定義一條路線:
const routes: Routes = [
{
path: 'stuff/info',
component: InfoComponent,
}
]
然后,您可以使用.navigate或routerLink添加可選參數,如下圖所示。
注意:從Angular 4開始,這應該是
this.route.snapshot.paramMap.get('start')
另外,您可以始終傳遞id並在創建時傳遞0或其他一些已知值。 我在這里有一個完整的示例: https : //github.com/DeborahK/Angular-Routing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.