假设你有一个这样的组件:
import { Component, OnInit } from '@angular/core';
import { ActivationEnd, Router } from '@angular/router';
@Component({
selector: 'app-test-router',
templateUrl: './test-router.component.html',
styleUrls: ['./test-router.component.css']
})
export class TestRouterComponent implements OnInit {
section = '';
dynamicSubNavLabel = '';
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe(e => {
if (e instanceof ActivationEnd) {
this.section = e.snapshot.data.title;
this.dynamicSubNavLabel = e.snapshot.routeConfig?.data?.label;
}
});
}
}
因为已经Router.events
是Subject<Event>
。我们可以完成这个:
- 我们将它转换为
Subject<Event>
然后调用next
以发出我们的自定义/模拟 ActivationEnd 事件。
- 首先将我们的模拟数据转换为 unknown,然后再转换为 ActivatedRouteSnapshot。
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, ActivationEnd, Event, Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { Subject } from 'rxjs';
import { TestRouterComponent } from './test-router.component';
describe('TestRouterComponent', () => {
let component: TestRouterComponent;
let fixture: ComponentFixture<TestRouterComponent>;
let router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [ TestRouterComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TestRouterComponent);
component = fixture.componentInstance;
router = TestBed.inject(Router);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should update data from router', () => {
const events$ = router.events as Subject<Event>;
const mockSnapshot = {
data: {
title: 'some heading'
},
routeConfig: {
data: {
label: 'some text'
}
}
} as unknown as ActivatedRouteSnapshot;
events$.next(new ActivationEnd(mockSnapshot));
expect(component.section).toBeTruthy();
expect(component.dynamicSubNavLabel).toBeTruthy();
})
});
来自 Angular 的源代码:https ://github.com/angular/angular/blob/75a3c778b1f7be913f0287423d40fade68ee9adc/packages/router/src/router.ts#L461