Angular 2 - 对每个http请求附加withCredentials = true

时间:2016-09-28 09:40:08

标签: angular angular-cli angular2-providers

我正在使用angular 2(不是最新的使用通过angular-cli:1.0.0-beta.11-webpack.9-4),我必须为每个http请求设置withCredentials为true。我尝试使用

为一个请求设置它

http.get(' http://my.domain.com/request',{withCredentials:true})

并且一切正常但是我正在尝试使用bootstrap中的内容,如下所示但没有取得任何成功

import './polyfills.ts';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';
import {Http, Headers, BaseRequestOptions, RequestOptions, BrowserXhr} from '@angular/http';

if (environment.production) {
  enableProdMode();
}

export class MyRequestOptions extends BaseRequestOptions {
  constructor () {
    super();
    this.headers.append('withCredentials','true');
  }
}

platformBrowserDynamic().bootstrapModule(AppModule, 
  [{ provide: RequestOptions, useClass: MyRequestOptions}]
);

2 个答案:

答案 0 :(得分:3)

我不知道是否需要它,但我遇到了同样的问题而且我已经用这种方式解决了:

  1. 创建BaseRequestOptions的子类(扩展RequestOptions):

    import { Headers, BaseRequestOptions } from "@angular/http";
    
    export class AuthRequestOptions extends BaseRequestOptions {
       constructor() {
          super();
          this.withCredentials = true;
       }
    }
    
  2. 在应用程序引导程序中注册

    import { RequestOptions } from '@angular/http';
    import { AuthRequestOptions } from './<path>/AuthRequestOptions';
    
    @NgModule({
       bootstrap: [...],
       imports: [...],
       providers: [
          { provide: RequestOptions, useClass: AuthRequestOptions},
          ...
       ]
    }...
    
  3. (在我的情况下,这适用于CORS + NTLMAuthentication)

答案 1 :(得分:0)

Sierrodc所示,Angular 4.3+允许拦截器使用来配置它。与NTLMAuthentication一起使用的完整示例如下所示:

拦截器

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {


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

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

        return next.handle(request);
    }
}

模块配置(拦截器允许与其他拦截器堆叠):

@NgModule({
    imports: [CommonModule, BasicRoutingModule, HttpClientModule],
    declarations: [HomeComponent, CounterComponent, FetchDataComponent],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: WithCredentialsInterceptor,
            multi: true
        },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: BaseUrlInterceptor,
            multi: true
        }
    ]
})
export class BasicModule { }

实际使用情况

constructor(
    private http: HttpClient) {

    this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
        .subscribe(result => {
            this.forecasts = result;
        },
        error => {
            console.error(error);
        });
}