Я создал сервис, который в основном находит список маршрутов, по которым он проходит. Ниже приведен сервис, который отлично работает с вызовом routerUR маршрутизатора внутри любого компонента.
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class RoutingStateService {
private routeHistory = [];
constructor(
private router: Router
) {}
public loadRouting(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(({urlAfterRedirects}: NavigationEnd) => {
this.routeHistory = [...this.routeHistory, urlAfterRedirects];
});
}
public getHistory(): string[] {
return this.routeHistory;
}
public getPreviousUrl(): string {
return this.routeHistory[this.routeHistory.length - 2] || '/index';
}
}
Он добавляется в app.module поставщикам и внедряется в AppComponent
constructor(routingState: RoutingStateService) {
routingState.loadRouting();
});
* 1006. * наконец, используя их в выборке компонентов getPreviousURL
Ниже приведен пример модульного теста, который я создал. Я нахожу проблемы со вторым модульным тестовым кодом для getHistory (). Он всегда возвращает 0. Я ожидаю 2. Я думаю, что мне не хватает некоторых важных моментов.
import { TestBed, inject, fakeAsync, flushMicrotasks } from '@angular/core/testing';
import { RoutingStateService } from './routing-state.service';
import { Router, NavigationEnd } from '@angular/router';
import { from } from 'rxjs';
const routerStub = {
events: from(
[
{ urlAfterRedirects: 'path1' } as NavigationEnd,
{ urlAfterRedirects: 'path2' } as NavigationEnd
])
};
describe('RoutingStateService', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [RoutingStateService,
{ provide: Router, useValue: routerStub},
]
}).compileComponents());
it('should be created', () => {
const service: RoutingStateService = TestBed.get(RoutingStateService);
expect(service).toBeTruthy();
});
it('should be created history', fakeAsync(
inject([RoutingStateService], (service: RoutingStateService) => {
service.loadRouting();
flushMicrotasks();
expect(service.getHistory().length).toEqual(2);
})));
});