3

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

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

一切正常,但是我试图在引导程序中使用如下所示的东西,但没有取得任何成功

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}]
);
4

2 回答 2

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},
          ...
       ]
    }...
    

(就我而言,这是与 CORS+NTLMAuthentication 一起使用的)

于 2017-04-08T20:57:00.663 回答
0

正如SierrodcAngular 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);
        });
}
于 2018-04-10T15:45:08.480 回答