背景
为了做一个面包屑的样式
思路
三个界面:
根页面: index(展示面包屑)
资金页面: fund(展示收入、支出,属于同一个页面)
步骤:
在index服务中存BehaviorSubject类型的变量crumbData,
在found组件中监听路由变化,根据路由参数设置不同的面包屑数据,
在index组件中订阅crumbData变量
出现的问题:
如果不用BehaviorSubject订阅,直接设为一个列表,在更新时,会报错:数据已经检查后被修改ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
源码
src\app\pages\index\index.component.html
<li nz-menu-item (click)="navigate('/found', 0)">村收入</li>
<li nz-menu-item (click)="navigate('/found', 1)">村支出</li>
<nz-breadcrumb>
<ng-container *ngFor="let item of crumbData">
<nz-breadcrumb-item >{{item}}</nz-breadcrumb-item>
</ng-container>
</nz-breadcrumb>
<router-outlet></router-outlet>
src\app\pages\index\index.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
declare const document: any;
import { IndexService } from './index.service';
@Component({
selector: 'k-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent{
constructor(
private route: Router,
public indexService: IndexService,
) {
this.indexService.crumbData.subscribe((x) => {
this.crumbData = x
});
}
// 面包屑数据
public crumbData: any = ['首页']
navigate(url: any, type?: any) {
this.route.navigate([url], { queryParams: { type: type } })
}
}
src\app\pages\index\index.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class IndexService {
// 面包屑数据
public crumbData = new BehaviorSubject<any>(['首页']);
setData(data: any) {
this.crumbData.next(data);
}
}