每次HttpClient调用时,Angular 6将withCredentials设置为true

Fre*_*nda 1 http apache-commons-httpclient angular

如果希望凭据(cookie身份验证令牌)可通过调用传递,则需要添加{ withCredentials: true }httpclient调用。像这样:

import { HttpClient  } from '@angular/common/http';
...
constructor(private httpclient: HttpClient) { }

this.httpclient.get(url, { withCredentials: true })
Run Code Online (Sandbox Code Playgroud)

我只想知道是否有一种方法可以{ withCredentials: true }对每个呼叫进行预设。我不想{ withCredentials: true }每次打电话时都添加。

这是一个相关的问题,但是我不确定这是否适用于HttpClient

Sac*_*aka 5

创建一个 HttpInterceptor

@Injectable()
export class CustomInterceptor implements HttpInterceptor { 

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomInterceptor ,
      multi: true
    }
  ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)