Angular路由器在http拦截器中无法导航。
创始人
2024-10-28 03:33:08
0

在Angular中,当我们使用HTTP拦截器时,我们无法使用路由器进行导航,因为路由器依赖于DOM,而HTTP拦截器在DOM之前执行。

但是,我们可以使用Angular的RouterTestingModule来模拟路由器,并在测试中使用它来进行导航。

以下是一个示例解决方法:

  1. 创建一个MockRouter类,模拟路由器的navigate方法。
class MockRouter {
  navigate = jasmine.createSpy('navigate');
}
  1. 在你的HTTP拦截器中注入Router,并使用RouterTestingModule进行导航。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Router } from '@angular/router';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(private router: Router) {}

  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    // 在需要导航的地方使用这个条件
    if (request.url.includes('navigate')) {
      const mockRouter = new MockRouter();
      mockRouter.navigate(['/example']);
    }

    return next.handle(request);
  }
}
  1. 在测试中使用RouterTestingModule模拟路由器,并注入MyInterceptor
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { MyInterceptor } from './my-interceptor';

describe('MyInterceptor', () => {
  let interceptor: MyInterceptor;
  let httpMock: HttpTestingController;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      providers: [MyInterceptor]
    }).compileComponents();
  }));

  beforeEach(() => {
    interceptor = TestBed.inject(MyInterceptor);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('should navigate when URL includes "navigate"', () => {
    spyOn(interceptor['router'], 'navigate');

    const req = httpMock.expectOne('/api/navigate');
    req.flush({});

    expect(interceptor['router'].navigate).toHaveBeenCalledWith(['/example']);
  });
});

通过使用RouterTestingModule和模拟路由器,我们可以在HTTP拦截器中进行导航,并在测试中验证导航是否发生。

相关内容

热门资讯

经核实!pokemmo辅助官网... 您好:pokemmo辅助官网这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
现场直击!wepoker辅助分... wepoker辅助分析器 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...
不少玩家反映!we-poker... 不少玩家反映!we-poker辅助(透视)原来真的是有挂(有挂工具开挂辅助神器)-哔哩哔哩>>您好:...
为了进一步!wpk有那种辅助吗... 为了进一步!wpk有那种辅助吗(透视)其实确实有挂(有挂详细开挂辅助软件)-哔哩哔哩;无需打开直接搜...
近年来!微信小游戏万能修改器(... 近年来!微信小游戏万能修改器(辅助挂)原来真的是有挂(有挂步骤)-哔哩哔哩;无需打开直接搜索薇:13...
据通报!新玄龙开挂图片(辅助挂... 据通报!新玄龙开挂图片(辅助挂)原来确实有挂(有挂步骤)-哔哩哔哩《详细加薇136704302咨询》...
不少玩家反映!约局吧游戏挂(透... 您好:这款约局吧游戏挂游戏是可以开挂的,确实是有挂的,很多玩家在这款约局吧游戏挂游戏中打牌都会发现很...
无独有偶!wepoker俱乐部... 无独有偶!wepoker俱乐部辅助(透视)原来确实有挂(证实有挂开挂辅助软件)-哔哩哔哩;无需打开直...
今日!中至上饶神辅助(辅助挂)... 中至上饶神辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信...
无独有偶!德扑圈透视挂(透视)... 无独有偶!德扑圈透视挂(透视)果然真的有挂(有挂讲解开挂辅助软件)-哔哩哔哩;无需打开直接搜索微信(...