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

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

最佳答案

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

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

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

    import { RequestOptions } from '@angular/http';
    import { AuthRequestOptions } from './<path>/AuthRequestOptions';
    
    @NgModule({
       bootstrap: [...],
       imports: [...],
       providers: [
          { provide: RequestOptions, useClass: AuthRequestOptions},
          ...
       ]
    }...
    

(在我的例子中,这是与 CORS+NTLMAuthentication 一起工作的)

关于Angular 2 - 在每个 http 请求中附加 withCredentials = true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39743624/

相关文章:

javascript - 这 3 个 Angular2 命令导入什么?

unit-testing - 使用 MockBackend 的 Angular 4 测试返回 Promise

angular-cli - 角度 Cli : disable live reload from browser's console

angular - 在模型类 Angular 中注入(inject)服务

javascript - 在 Angular2 中包含外部(托管)JavaScript 文件

typescript :在编译时在自己的属性中获取类名

unit-testing - 带有模拟的 Angular 2 TestBed

Angular2 模块 : How can i import a service from another module

javascript - 防止为未打开的扩展面板呈现内部 html

Angular 4 应用程序可在本地运行但无法在 Github 中加载