能够通过订阅路由器事件来获取构造函数中的上一个URL。登录并签入了构造函数,但单击返回时,按钮无法将其导入该方法。
构造函数:
previousUrl: string;
constructor(
private router: Router,
) {
this.router.events
.pipe(filter((e: any) => e instanceof RoutesRecognized),
pairwise()
).subscribe((e: any) => {
this.previousUrl = e[0].urlAfterRedirects;
console.log('this is it' + this.previousUrl); // previous url
});
}
goBack():
goBack() {
console.log('******************************' + this.previousUrl);
this.router.navigate([ this.previousUrl ]);
}
答案 0 :(得分:0)
尝试以下对我有用的代码段
路由器服务:
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Injectable()
export class RouterService {
previousUrl: string = 'none';
constructor(
private router: Router
) {
this.router.events
.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.previousUrl = event.url;
}
});
}
}
在您的组件中
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-some',
template: `<span *ngIf="prevUrl !== 'none'>Back</span>`,
styles: [``]
})
export class SomeComponent implements OnInit {
prevUrl;
constructor(private routerService: RouterService) {
this.prevUrl == routerService.previousUrl;
}
ngOnInit() { }
}
goBack() {
console.log('******************************' + this.prevUrl );
this.router.navigate([ this.prevUrl ]);
}