我正在尝试创建服务,以使该服务中的所有API调用都不会附加令牌。我使用HttpBackend实现了这一点。但是现在ng-http-loader对于这些API无效。
ng-http-loader在通过HttpBackend处理的API调用中工作。
@Injectable()
export class HomeHttpService {
private http: HttpClient;
constructor(handler: HttpBackend) {
this.http = new HttpClient(handler);
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
TooltipModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
NgbModule,
AuthModule,
AppRoutingModule,
ToastrModule.forRoot(),
NgHttpLoaderModule.forRoot()
],
providers: [
{ provide: ErrorHandler, useClass: ErrorsHandler },
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
<router-outlet></router-outlet>
<ng-http-loader [backdrop]="true" [debounceDelay]="100" [extraDuration]="300" [minDuration]="300" [opacity]="0.6" [backgroundColor]="'#767676'" [spinner]="spinkit"></ng-http-loader>
import { HomeHttpService } from '../home-http.service';
import { Observable } from 'rxjs';
import { environment } from 'environments/environment';
@Injectable()
export class APIService {
constructor(private apiservice: HomeHttpService) {}
ng-http-loader正在处理来自api.service.ts以外的所有其他服务的api调用
讨论了之后,这里是重点。
[在HttpBackend
中提供HttpClient
时,它将忽略所有拦截器,因此ng-http-loader
将不起作用,因为它不知道请求。
现在可以通过将标题与请求一起使用来解决here。
拦截器
export const InterceptorSkipHeader = 'X-Skip-Interceptor';
@Injectable()
export class SkippableInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.has(InterceptorSkipHeader)) {
const headers = req.headers.delete(InterceptorSkipHeader);
return next.handle(req.clone({ headers }));
}
... // intercept
}
}
现在,从服务中,对于您不希望拥有拦截器的API,可以设置此标头。
const headers = new HttpHeaders().set(InterceptorSkipHeader, '');
this.httpClient.get(someUrl, { headers })
...