ng-docs.github.io
ng-docs.github.io copied to clipboard
拦截器为什么会触发两次?
import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Router} from '@angular/router';
import {tap} from 'rxjs/operators';
import {Observable} from 'rxjs';
@Injectable()
export class Interceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(req);
const c = req.clone({
url: '/test/' + req.url,
withCredentials: true
});
// debugger;
return next.handle(c).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
console.log(event);
switch (event.body.code) {
case 'no_login':
this.router.navigate(['/login']);
}
}
},
error => {
console.error(error);
}
)
);
}
}
然后在modue中
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BootRoutingModule } from './boot-routing.module';
import { ErrorComponent } from './error/error.component';
import {BootComponent} from './boot/boot.component';
import { LoginComponent } from './login/login.component';
import { AbsPipe } from './pipe/abs.pipe';
import {HttpClientModule} from '@angular/common/http';
import {Interceptor} from './interceptor/interceptor';
import {CommunicationService} from './service/communication.service';
@NgModule({
declarations: [
BootComponent,
ErrorComponent,
LoginComponent,
AbsPipe
],
imports: [
BrowserModule,
BootRoutingModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: Interceptor,
multi: true
},
CommunicationService
],
bootstrap: [BootComponent]
})
export class BootModule { }
这样写会触发两次拦截器,但是只发起了一次请求。 如果我请求的URL是‘/getfunc’,我想要的是‘/test/getfunc’,最后发起请求的却是‘/test/test/getfunc’ 请问一下这是为什么? 我的angular版本是 ` Angular CLI: 6.2.9 Node: 11.14.0 OS: darwin x64 Angular: 6.1.10 ... animations, common, compiler, compiler-cli, core, forms ... http, language-service, platform-browser ... platform-browser-dynamic, router
Package Version
@angular-devkit/architect 0.8.9 @angular-devkit/build-angular 0.8.9 @angular-devkit/build-optimizer 0.8.9 @angular-devkit/build-webpack 0.8.9 @angular-devkit/core 0.8.9 @angular-devkit/schematics 0.8.9 @angular/cli 6.2.9 @ngtools/webpack 6.2.9 @schematics/angular 0.8.9 @schematics/update 0.8.9 rxjs 6.2.2 typescript 2.9.2 webpack 4.16.4 `
到 stackblitz 做个 live demo?