我正在为我的项目做面包屑。我这里有两个问题:
如何解决这两个问题?
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, RoutesRecognized, NavigationStart, NavigationEnd, Params, PRIMARY_OUTLET } from '@angular/router';
import { filter, map } from 'rxjs/operators';
import { BreadCrumbsService } from './../../services/bread-crumbs.service';
@Component({
selector: 'bread-crumbs',
templateUrl: './bread-crumbs.component.html',
styleUrls: ['./bread-crumbs.component.scss']
})
export class BreadCrumbsComponent implements OnInit {
breadcrumbList: Array<any> = [];
/**
* Setting Breadcrumb object, where name for display, path for url match,
link for heref value, getting datas from BreadCrumbsService service
*/
constructor(private router: Router, private bCService: BreadCrumbsService) {
this.generateBreadCrumb();
}
ngOnInit() {}
generateBreadCrumb() {
console.log('hi');
let routerUrl: string, routerList: Array<any>, target: any;
this.router.events.subscribe((router: any) => {
console.log('do'); //not consoles on above 2 points
routerUrl = router.urlAfterRedirects;
});
}
}
上述解决方案对我不起作用。我想出了以下解决方案
export BreadcrumbComponent implements OnInit {
isRefreshed = true; // dummy variable flag
constructor(private router: Router, private activatedRoute: ActivatedRoute, public breadcrumbService: FinlexBreadcrumbService) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
distinctUntilChanged()
)
.subscribe(() => {
//Build your breadcrumb starting with the root route of your current activated route. will call only on navigation change
this.isRefreshed = false;
this.breadcrumbService.buildBreadCrumb(this.activatedRoute.firstChild);
});
}
ngOnInit(): void {
if (this.isRefreshed) {
//will call only when page reload happens
this.breadcrumbService.buildBreadCrumb(this.activatedRoute.firstChild);
}
}
}
我正在使用的路由器订阅逻辑更具限制性并且有效:
constructor(private router: Router) {
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
console.log(event.urlAfterRedirects);
}
});
}
所以我认为您的问题是由您设置路由器模块的方式引起的。 您是否通过在两个 URL 中使用两个组件来测试路由器是否正常工作? 或者您愿意与我们分享您的路由器模块吗?
我在条件中添加了另一种类型的事件,它解决了我的问题:
constructor(private router: Router) {
router.events
.pipe(filter((event: any) => event instanceof NavigationEnd || event instanceof Scroll))
.subscribe((val: any) => {
console.log(val.url || val.routerEvent.url);
})
}
可能是因为您的组件稍后渲染根组件,最好从根组件创建服务并初始化路由监视服务方法