在本教程中,我们将了解如何检测由 角度的 路由器更改事件。
另外,我们将了解如何通过为角度路由器事件创建模拟类来覆盖事件的单元测试用例。
路由器变更事件
可以通过订阅路由器并侦听正在发出的事件来检测路由状态更改。在下面的示例中,您将看到可以在Angular 8中侦听的所有路由器事件。
路由器事件列表:
大事记 | 描述 |
---|---|
NavigationStart | 导航开始。 |
公认路线 | 路由器解析URL,并识别出路由。 |
RouteConfigLoadEnd | 路线已被延迟加载。 |
导航结束 | 导航成功结束。 |
导航取消 | 由于导航期间Route-Guard返回false,因此导航被取消。 |
NavigationError | 导航由于意外错误而失败。 |
路由器事件的实现:
app.component.ts
import { Component } from '@angular/core';
import { Router, Event, NavigationStart, 公认路线,
RouteConfigLoadStart, RouteConfigLoadEnd,
NavigationEnd, 导航取消, NavigationError } from '@angular/router';
@Component({
selector: 'demo-app',
template: `<router-outlet></router-outlet>`
})
export class DemoAppComponent {
constructor(private router: Router) {
router.events.subscribe( (event: Event) =>
if (event instanceof NavigationStart) {
// 导航开始。
console.log(event.url);
}
else if (event instanceof 公认路线) {
// 路由器解析URL,并识别出路由。
}
else if (event instanceof RouteConfigLoadStart) {
// Before the Router lazyloads a route configuration.
}
else if (event instanceof RouteConfigLoadEnd) {
// 路线已被延迟加载。
}
else if (event instanceof 导航结束) {
// 导航成功结束。
console.log(event.url);
}
else if (event instanceof 导航取消) {
// 由于导航期间Route-Guard返回false,因此导航被取消。
}
else if (event instanceof NavigationError) {
// 导航由于意外错误而失败。
console.log(event.error);
}
});
}
}
注意: 大事记 are triggered where ever
console.log()
is mentioned.路由器事件的单元测试
对于单元测试,我们将为以下场景创建一个模拟类 NavigationStart
app.component.spec.ts
import { AppComponent } from './app.component';
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable, Observer } from 'rxjs';
// mock router service
class MockServices {
public events = Observable.create((observer: Observer<any>) => {
observer.next(new NavigationStart(0, 'http://127.0.0.1:3001/dummy/url', 'imperative'));
return observer;
});
}
describe('AppComponent', () => {
let instance: AppComponent;
let fixture: ComponentFixture<appcomponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ],
imports: [
],
providers: [
{ provide: Router, useClass: MockServices },
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
}));
});
同样,您还可以根据情况涵盖其他角度路由器事件。
获取有关的更多教程 角度8+