角度2:基于环境的导入服务 [英] Angular 2: Import service based on environment

查看:103
本文介绍了角度2:基于环境的导入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular-cli项目中基于当前环境导入服务的最佳/正确方法是什么?

What is the best/proper way to import a service based on the current environment within an angular-cli project?

我已经建立了一个名为dev-mock的新环境,可以用...调用它.

I have setup up a new environment called dev-mock which I can call with ...

ng serve --environment=mock

然后我使用useClass在模块中设置提供程序

I then set up the provider in the module with useClass

app/app.module.ts ...

app/app.module.ts ...

import {environment} from '../environments/environment';
import {ApiService} from './api/api.service';
import {MockApiService} from './api/mock/mock-api.service';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
    {
      provide: ApiService,
      useClass: (environment.name === 'dev-mock') ? MockApiService : ApiService
    }
  ],
  bootstrap: [AppComponent]
})

这很好用,那么问题是当我要将其注入到另一个服务或组件中时该怎么办...

This works fine, the problem then is what do I do when I want to inject that into another service or component, for example ...

app/ticket/ticket.service.ts

app/ticket/ticket.service.ts

import {ApiService} from '../api/api.service'; // *** WHAT AM I TO DO HERE? ***

@Injectable()
export class TicketService {

  constructor(private api: ApiService, private http: Http) {
  }

}

很明显,我的方法是错误的.正确的方法是什么?

Obviously my approach is wrong. What is the correct approach?

推荐答案

为MockApiService和ApiService创建接口,例如. IApiService.如果要交换它们,则必须有一个.

Create interface for MockApiService and ApiService eg. IApiService. If you want to interchange them there has to be one.

使用令牌创建文件并将其导出:

Create a file with token and export it:

import { OpaqueToken } from '@angular/core';
export let API_SERVICE = new OpaqueToken('api.service');

然后使用令牌在某处注册您的服务:

Then register your service somewhere using the token:

const apiServiceClass = (environment.name === 'dev-mock') ? MockApiService : ApiService;

providers: [{ provide: API_SERVICE, useClass: apiServiceClass }]

最后,您可以使用构造函数中应用的Inject()装饰器在任何地方使用它.

Finally you can use it in any place using Inject() decorator applied in constructor, eg.

import {IApiService} from '../api/iapi.service';
import { Inject, Injectable } from '@angular/core';

@Injectable()
export class TicketService {

  constructor(@Inject(API_SERVICE) private api: IApiService) {}
}

诀窍是将接口作为属性的类型,并使用Inject()和OpaqueToken来告诉依赖关系注入器应该放置什么.

The trick is to gice interface as type of property and use Inject() with OpaqueToken to tell dependency injector what it should put.

这篇关于角度2:基于环境的导入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆