例如,我的網址是www.mywebsite.com/a/b/c,我想轉到www.mywebsite.com/a/b
我嘗試過使用 route.navigate(['..']) 但它回傳了一些遺留的東西并且沒有任何事情發生。
uj5u.com熱心網友回復:
如果您想以適當的方式做到這一點,有一個很好且強大的解決方案。
這個網站上有很多答案只是簡單地推薦使用服務back()中的方法Location。但是,請注意,這種方法存在邊緣情況,如果用戶打開一個新選項卡,歷史記錄中將沒有條目可以回傳。這可能會使用戶退出 Angular 應用程式并引入安全問題,因為沒有用于直接檢查瀏覽器歷史記錄的 API。
以下解決方案基于Nils Mehlhorn的博客文章
導航服務
import { Injectable } from '@angular/core'
import { Location } from '@angular/common'
import { Router, NavigationEnd } from '@angular/router'
@Injectable({ providedIn: 'root' })
export class NavigationService {
private history: string[] = []
constructor(
private router: Router,
private location: Location
) {
// Listen to router events of type NavigationEnd to
// manage an app-specific navigation history.
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.history.push(event.urlAfterRedirects);
}
})
}
/**
* Manage back navigation.
*/
back(): void {
this.history.pop();
// If the history still contains entries after popping
// the current URL off of the stack, we can safely
// navigate back. Otherwise we're falling back to the
// application root.
if (this.history.length > 0) {
console.log('navigating back')
this.location.back();
} else {
console.log('navigating to /')
this.router.navigateByUrl('/');
}
}
}
后退按鈕指令
import { Directive, HostListener } from '@angular/core';
import { NavigationService } from './navigation.service';
@Directive({
selector: '[navigateBack]',
})
export class BackButtonDirective {
constructor(private navigation: NavigationService) {}
@HostListener('click')
onClick(): void {
this.navigation.back();
}
}
在 HTML 中使用指令
<button navigateBack>
<mat-icon>arrow_back</mat-icon>Back
</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529105.html
標籤:有角度的打字稿重定向路线
