有没有办法将后端呈现的参数传递给angular2 bootstrap 方法?我想使用BaseRequestOptions为所有请求设置http头,并从后端提供值.我的main.ts文件如下所示:

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from "./app.component.ts";

bootstrap(AppComponent);

我发现了如何将此参数传递给根组件(https://stackoverflow.com/a/35553650/3455681),但是我在激发bootstrap方法时需要它……有什么主意吗?

edit:

webpack.config.js内容:

module.exports = {
  entry: {
    app: "./Scripts/app/main.ts"
  },

  output: {
    filename: "./Scripts/build/[name].js"
  },

  resolve: {
    extensions: ["", ".ts", ".js"]
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'ts-loader'
      }
    ]
  }
};

推荐答案

update2

Plunker example

update AoT

为了与AoT合作,工厂关闭需要迁出

function loadContext(context: ContextService) {
  return () => context.load();
}

@NgModule({
  ...
  providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: loadContext, deps: [ContextService], multi: true } ],

另见https://github.com/angular/angular/issues/11262

update元人民币.6和2.0.0最终示例

function configServiceFactory (config: ConfigService) {
  return () => config.load();
}

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule,
        routes,
        FormsModule,
        HttpModule],
    providers: [AuthService,
        Title,
        appRoutingProviders,
        ConfigService,
        { provide: APP_INITIALIZER,
          useFactory: configServiceFactory
          deps: [ConfigService], 
          multi: true }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

如果不需要等待初始化完成,也可以使用`class AppModule{}的构造函数:

class AppModule {
  constructor(/*inject required dependencies */) {...} 
}

hint (cyclic dependency)

例如,注入路由可能会导致循环依赖.

this.myDep = injector.get(MyDependency);

而不是直接注射MyDependency,比如:

@Injectable()
export class ConfigService {
  private router:Router;
  constructor(/*private router:Router*/ injector:Injector) {
    setTimeout(() => this.router = injector.get(Router));
  }
}

update

在RC中也应该如此.5,而是将提供程序添加到根模块的providers: [...],而不是bootstrap(...)

(我自己还没有测试过).

update

这里解释了一种完全在Angular 内完成的有趣的方法,https://github.com/angular/angular/issues/9047#issuecomment-224075188

您可以使用APP_INITIALIZER,当

例如,假设您有一个多租户解决方案

在bootstrap中:

{provide: APP_INITIALIZER, useFactory: (sites:SitesService) => () => sites.load(), deps:[SitesService, HTTP_PROVIDERS], multi: true}),

地点.服务ts:

@Injectable()
export class SitesService {
  public current:Site;

  constructor(private http:Http, private config:Config) { }

  load():Promise<Site> {
    var url:string;
    var pos = location.hostname.lastIndexOf(this.config.rootDomain);
    var url = (pos === -1)
      ? this.config.apiEndpoint + '/sites?host=' + location.hostname
      : this.config.apiEndpoint + '/sites/' + location.hostname.substr(0, pos);
    var promise = this.http.get(url).map(res => res.json()).toPromise();
    promise.then(site => this.current = site);
    return promise;
  }

注意:config只是一个自定义配置类.rootDomain美元是 '.letterpress.com'用于此示例,并允许执行以下操作 aptaincodeman.letterpress.com.

任何组件和其他服务现在都可以注入Site

此方法似乎缩短了启动延迟,否则 很明显,如果你在等待大的角形束 加载,然后在 bootstrap 开始之前加载另一个http请求.

original

您可以使用Angulars依赖项注入传递它:

var headers = ... // get the headers from the server

bootstrap(AppComponent, [{provide: 'headers', useValue: headers})]);
class SomeComponentOrService {
   constructor(@Inject('headers') private headers) {}
}

或者直接提供

class MyRequestOptions extends BaseRequestOptions {
  constructor (private headers) {
    super();
  }
} 

var values = ... // get the headers from the server
var headers = new MyRequestOptions(values);

bootstrap(AppComponent, [{provide: BaseRequestOptions, useValue: headers})]);

Angular相关问答推荐

iOS Mobile Safari - HTML5视频覆盖一切

Angular 17自定义指令渲染不起作用'

如何在Angular中执行一个操作条件为多个可观测值?

Angular 升级到v16和Ant设计错误:';nzComponentParams';类型';ModalOptions';中不存在

停靠的Angular 应用程序的Nginx反向代理无法加载assets资源

仅在从forkJoin获得数据后订阅主题

截获火灾前调用公共接口

当我更新S显示的数据时,为什么我的垫表用户界面没有更新?

Angular-每2个流式传输多个HTTP调用

Cypress 12.8.1 无法使用条纹元素 iframe

Angular 15:在范围内提供相同标记时附加到提供的值

需要做什么才能使 ErrorHandler 正常工作?

如何以Angular 显示动态视图模型

如何重置表单中的特定字段?

如何从表单组中禁用的表单控件中获取值?

无法读取 angular2 中未定义(…)的属性 push

Error: Module not found: Error: Can't resolve '@angular/cdk/scrolling'

如何以编程方式触发`valueChanges`?

为什么 Angular 项目中没有 Angular-CLI 为 model生成命令?

如何将从后端渲染的参数传递给angular2 bootstrap 方法