我定义了一些与某些组件匹配的路由,然后有了一个带有占位符的全包路由,如下所示:
const routes: Routes = [
{ path: 'some', component: SomeComponent },
{ path: 'other', component: OtherComponent },
{ path: ':route', component: PageNotFoundComponent }
];
然后我有一个这样的PageNotFoundComponent:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-page-not-found',
templateUrl: './page-not-found.component.html',
styleUrls: ['./page-not-found.component.css']
})
export class PageNotFoundComponent implements OnInit {
missingRoute: string;
route: any;
constructor( route: ActivatedRoute ) {
this.route = route;
}
ngOnInit() {
this.missingRoute = this.route.snapshot.paramMap.get('route');
}
}
和PageNotFoundComponent的html文件,如下所示:
<p>The route {{missingRoute}} is not implemented.</p>
我有一个带有一些路由器链接和路由器插座的组件(此处未显示)。如果我单击 some 和 other 的路由器链接,则可以正常工作-从某种意义上说,这些组件显示在路由器插座上。我也有两个链接到“ doesnotexist ”和“ doesnotexist2 ”的路由器链接。如果我去dosnotexist,这将正确显示(PageNotFound告诉我),但是如果我再单击dosnotexist2,我将得到与dosnotexist相同的信息:“路由donotexist未实现。”。我希望得到“路由donotexist2未实现。”
我想念什么?
答案 0 :(得分:1)
之所以发生这种情况,是因为您试图导航到同一根,仅更改了路由参数。因此,为了获取更改的参数而不是使用this.route.snapshot.paramMap.get('route');
,只需订阅路由参数,例如
this.route.params.subscribe(data=>{
this.missingRoute =data['route']
});
为什么不简单地在构造函数注入中使用private关键字,而不是定义属性和分配类似对象
constructor(private route: ActivatedRoute ) {
}
答案 1 :(得分:1)
在您的路线配置中,您缺少此信息:
{ path: '**', component: PageNotFoundComponent }
一旦有了这个,就必须捕获请求的路线,以便显示missingRoute
。 docs
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) {
return true;
}
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}