簡體   English   中英

Angular router.navigate 在 MatDialog 中不起作用

[英]Angular router.navigate is not working in MatDialog

我有 NewCategoryComponent,它具有獲取詳細信息的表單和將在用戶關閉表單時顯示的 WarningComponent。

單擊關閉(x)圖標時,用戶將收到警告消息( Mat Dialog ),“您確定要關閉嗎? ”。 然后用戶應該去上一條路線。

如果我當前的路線是category/101/newCategory ,它應該去category/101 我已經實現this.router.navigate(['../'], { relativeTo: this.activatedRoute }); .

問題

如果我保留this.router.navigate(['../'], { relativeTo: this.activatedRoute }); 在WarningComponent 中,它將轉到/ (根)位置。 在 NewCategoryComponent 中,它工作得非常好。

代碼

新類別組件

 // new-category.component.html <button mat-icon-button class="cancelBtn" (click)="showWarning()"> <mat-icon>close</mat-icon> </button> // new-category.component.ts showWarning(): void { this.matDialog.open(WarningComponent); // going to localhost:4200/category/101 // this.router.navigate(['../'], { relativeTo: this.activatedRoute }); // working }

警告組件

 // warning.component.html <button mat-raised-button class="wrnBtn stayBtn" (click)="stay()"> <span>Stay</span> </button> <button mat-raised-button class="wrnBtn closeBtn" (click)="close()"> <span>Close</span> </button> // warning.component.ts constructor( public warningDialog: MatDialogRef<WarningComponent>, private router: Router, private activatedRoute: ActivatedRoute ) { } close() { this.warningDialog.close(); this.router.navigate(['../'], { relativeTo: this.activatedRoute }); // not working properly } stay() { this.warningDialog.close(); }

如果要從此“ category / 101 / newCategory”轉到“ category / 101”路線。 然后執行以下操作:this.router.navigate(['/ category / 101']); 假設類別沒有父路線。 讓我知道它是否有效..

看起來這個問題已經在Github中報告了,到目前為止我找不到任何解決方案。

但是我創建了一個解決方法,它並不理想,但適用於 Angular 8。

因此,對於您的情況:

當前網址:/category/101/newCategory

目標網址:/category/101

// 1. solve the issue that Typescript thinks _routeState doesn't exist on Router
// we have to cast Router to any type to avoid compilation error
let r = this.router as any;

// 2. get current absolute url
let url = r.routerState.root._routerState.snapshot.url;

// 3. remove everything after the last forward slash
url = url.substring(0, url.lastIndexOf('/') + 1);

this.router.navigate([url]);

jist 是可以訪問絕對路徑,並且在擺脫 url 的最后一位之后導航到父組件。

暫無
暫無

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

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