【问题标题】:ng-http-loader not working for API calls handled via httpbackendng-http-loader 不适用于通过 httpbackend 处理的 API 调用
【发布时间】:2019-12-27 14:00:05
【问题描述】:

我试图创建一个服务,以便该服务中的所有 API 调用都不会附加令牌。我使用 HttpBackend 实现了这一点。但现在 ng-http-loader 不适用于这些 API。

我需要什么

ng-http-loader 在通过 HttpBackend 处理的 API 调用中工作。

主页-http.service.ts

@Injectable()
export class HomeHttpService {
  private http: HttpClient;
  constructor(handler: HttpBackend) {
    this.http = new HttpClient(handler);
  }

app.module.ts

    @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]
    })

app.component.html

 <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>

api.service.ts

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 调用

【问题讨论】:

  • api.service.ts 我没有看到handler 的设置?
  • handler 在 home-http.service 中设置。 api.service 是使用 home-http.service 编写 API 调用的地方
  • 你能提供stackblitz吗?
  • 我会试试的。之前没用过 StackBlitz
  • 最小表示会很有帮助。

标签: angular loader httpbackend


【解决方案1】:

讨论完这个,这里是重点。

当您在HttpClient 中提供HttpBackend 时,它将忽略所有拦截器,因此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 })
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2018-11-05
    • 2020-05-06
    相关资源
    最近更新 更多