如何在 angular2 rc4 中将数据加载到 bootstrap 上的服务

how to load data into service on bootstrap in angular2 rc4

场景如下。我注入了两项服务。我想确保一些数据,例如基础 url 被传递给第一个服务,以便所有后续服务都可以访问它。

这是我的根组件

export class AppCmp {

  constructor (private httpService:HttpService, private SomeService:someService){}

}

这是第一个服务,假设它是一个自定义的 httpSerive

 @Injectable()
    export class HttpService{
      BASE_URL:string;
      constructor(private http:Http){
      }
      getAll(){ return this.http.get(this.BASE_URL) }
    }

这里是第二个服务,它将依赖于第一个服务来执行 http.get 请求。

@Injectable()
export class SomeService{
  constructor(private httpSerivce:HttpSerivce){
    this.httpService.getAll()...
  }
}

我不想将基础 url(或数据)硬编码到服务中,我不想涉及 localStorages,所以我有两个选择:要么在 main.ts ( bootstrap 文件)或根组件,假设它们是分开的。

重要的是数据首先可用,并且可以传递给第一个注入的服务或由第一个注入的服务获取。

希望我能说明这个话题,谢谢!

你可以提供各种价值。

使用字符串键(或 OpaqueToken)注册提供商

{provide: 'BASE_URL', useValue: someUrl}

并像

一样注入
constructor(@Inject('BASE_URL') private baseURL:string)

对于 RC4main.ts

中执行此操作
let injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS);
let http = injector.get(Http);
let authService = new AuthService(new LocalStorage(),http);
authService.BASE_URL='you url goes here'


bootstrap(AppComponent, [ 
  APP_ROUTER_PROVIDERS,
  [provide(AuthService, {useValue: authService})],
]).catch(err => console.error(err));

这样做是 app.module.ts 但此代码适用于 RC5

您的服务:

let authService = new AuthService(new LocalStorage(), http);
authService.BASE_URL='you url goes here'

然后将其添加到提供者数组中

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [
    AppComponent
  ],
  providers: [
    {provide: AuthService, useValue: authService},
  ]
})