Angular2中的通配符嵌套路由
如何使用Angular 2路由器实现深度嵌套的通配符路由。所有通配符示例代码都倾向于处理未找到页面的示例。假设以下用例。您有一个在文件系统上充当文件夹查看器的程序。示例路线可能包括:Angular2中的通配符嵌套路由,angular,angular2-routing,Angular,Angular2 Routing,如何使用Angular 2路由器实现深度嵌套的通配符路由。所有通配符示例代码都倾向于处理未找到页面的示例。假设以下用例。您有一个在文件系统上充当文件夹查看器的程序。示例路线可能包括: /home/Documents/Personal /home/Pictures/Vacation/2015 /home/Pictures/Vacations/2015/10 到目前为止,我尝试了以下方法: const r = [ { path: 'home', component: Home
/home/Documents/Personal
/home/Pictures/Vacation/2015
/home/Pictures/Vacations/2015/10
const r = [
{
path: 'home',
component: HomeComponent,
children: [
{
path: '**',
component: FolderViewerComponent
}
]
}
];
export class FolderViewerComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute ) {
}
ngOnInit() {
console.log(this.route.url);
}
}
这类作品。我可以通过以下方式访问URL和部件:
const r = [
{
path: 'home',
component: HomeComponent,
children: [
{
path: '**',
component: FolderViewerComponent
}
]
}
];
export class FolderViewerComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute ) {
}
ngOnInit() {
console.log(this.route.url);
}
}
但是,当我在同一条路径上导航时,ngOnInit不会再次触发,因为新路径使用相同的组件。因此,我无法从服务器请求新文件夹内容
因此,在一天结束时:
我认为可能有更好的方法,但基于一些评论,我最终决定了以下几点。基本上,我订阅路由更改,并在更改时执行代码
import {Component, OnInit, OnDestroy} from '@angular/core';
import {Router} from '@angular/router';
import {Subscription} from 'rxjs';
@Component({
template: `...`
})
export class FolderViewerComponent implements OnInit, OnDestroy {
url: string;
routeSub: Subscription;
constructor(private router: Router) {
}
handleRouteChange(event) {
if (this.url !== event.url) {
this.url = event.url;
console.log(`Route changed to ${this.url}`);
// Whatever code you want
}
}
ngOnInit() {
this.routeSub = this.router.events.subscribe(this.handleRouteChange);
}
ngOnDestroy() {
this.routeSub.unsubscribe();
}
}
只需将url存储在vaiable中,并每次使用新的urlngOnInit()检查此变量{this.route.params.forEach(params:params)=>{//write code here}`