1 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為阻止后退按鈕不是一個(gè)好主意。您可以對(duì)請(qǐng)求使用緩存機(jī)制,這樣它就不會(huì)每次都將請(qǐng)求發(fā)送到服務(wù)器,而是獲得最新的響應(yīng)。請(qǐng)檢查這個(gè)例子:
const URL = 'https://api.punkapi.com/v2/beers';
@Injectable({
providedIn: 'root'
})
export class HttpService {
public responseCache = new Map();constructor(private http: HttpClient) {}public getBeerList(): Observable<any> {
const beersFromCache = this.responseCache.get(URL);
if (beersFromCache) {
return of(beersFromCache);
}
const response = this.http.get<any>(URL);
response.subscribe(beers => this.responseCache.set(URL, beers));
return response;
}
}
如果您仍然希望您的解決方案阻止用戶返回,則需要使用 Guards 來取消導(dǎo)航。
@Injectable()
export class MyGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
return !this.myService.stillDontWantToGoBack()
}}
這將適用于所有導(dǎo)航,如果您仍然只想要返回,則需要檢查您要訪問的 URL 是否與 previousUrl 相同。
我的服務(wù).service.ts
previousUrl: string;
constructor(router: Router) {
router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(e => {
console.log('prev:', this.previousUrl);
this.previousUrl = e.url;
});
}
在 my-guard.guard.ts
canActivate(route: ActivatedRouteSnapshot) {
return route.url !== this.myService.previousUrl;
}
添加回答
舉報(bào)