在Angular2中切换两个服务

时间:2016-07-18 21:03:08

标签: angular

让我说我有

import {ServerService} from './server-service'
import {ServerServiceMock} from './server-service-mock'

constructor (
    private serverService: ServerService
) {}

如何以编程方式切换让我们说两种服务之间的方法?毋庸置疑,有很多代码依赖于此。

或者也许可以进入服务本身?

export class AuthZeroLockService {
    if buttonSwitch == true {
        return {//normalservice}
    } else {
        return {//mockedservice}
    }
}

3 个答案:

答案 0 :(得分:3)

您可以使用factory provider根据应用程序的值动态实例化您的服务。

以下示例说明了如何使用factory provider

import { AppService } from './app.service';
import { AbstractDataService, DataService, MockedDataService } from './data.service';

let dataServiceFactory = (appService: AppService) => {
  // Example how to instantiate services conditionally
  return appService.State == 1 ? new DataService() : new MockedDataService();
};

export let DataServiceProvider = { 
  provide: AbstractDataService,
  useFactory: dataServiceFactory,
  deps: [AppService]
};

在您的组件上:

@Component({
  selector: 'my-app',
  template: `...`,
  providers: [AppService, DataServiceProvider] 
})
export class AppComponent { /* ... */ }

请参阅完整示例here

查看Angular有关Dependency Injection的文档以获取更多信息。

如果这种方法适合您,请告诉我。

答案 1 :(得分:1)

尝试这个

怎么样?
@Injectable
    export class AuthZeroLockService {
constructor (
    private serverService: ServerService, private mock: serverServiceMock
) {}
    getInstance()
    {
        if buttonSwitch == true {
            return {//normalservice}
        } else {
            return {//mockedservice}
        }
    }
    }

现在在您的组件中。

service:IServerService // interface implemented by both service 
constructor (
    private serverServiceFactory: AuthZeroLockService
) {
//you can call below code whenever you want to switch by wrapping in a method. 
this.service = serverServiceFactory.getInstance();
}

答案 2 :(得分:0)

不完全确定如何使用服务切换但是你不能做这样的事情:

import {ServerService} from './server-service'
import {ServerServiceMock} from './server-service-mock'

export class myComponent {

private service:<any>;

constructor (
    private serverService: ServerService,
    private mockService: ServerServiceMock
) {

   this.switchService(true);

}

private switchService(mock:boolean){
      this.service = (mock)? this.mockService : this.serverService;
}

}