簡體   English   中英

在TypeScript中調用Angular路由器

[英]Calling the Angular router in TypeScript

我在這樣的頁面中有一個按鈕:

<button [routerLink]="['../edit', 14]">Test</button>

所以,如果我在http://localhost/dashboard並單擊按鈕,我將被重定向到http://localhost/dashboard/edit/14 ,這正是我的預期。

現在我需要在Typescript中做同樣的事情。 我在我的課程中注入了Router服務並嘗試了以下方法:

this.router.navigate([`../edit/${item.id}`]);

this.router.navigate([`/edit/${item.id}`]);

this.router.navigate([`edit/${item.id}`]);

但沒有一個工作,所有這些都將我重定向到我的起始頁面,沒有任何錯誤。

Router是否需要一些額外的設置?

您需要指定相對於當前路由的路由。 以下是如何做到這一點:

@Component({...})
class ChildComponent {
  constructor(private router: Router, private route: ActivatedRoute) {}

  go() {
    this.router.navigate([`../edit/${item.id}`], { relativeTo: this.route });
  }
}

這是Docs描述NavigationExtras類的relativeTo屬性

請記住在app.module.ts上添加子路線:

RouterModule.forRoot(
    [{
        path: 'dashboard',
        component: Dashboard,
        children: [
            {
                path: 'edit/:id',
                component: EditComponent,
            }]
    }])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM