如何在Angular 7中通过deps和useValue有条件地使用不同的服务?

时间:2019-03-02 16:59:31

标签: angular7

你好,我正在练习angular7服务功能,并且想要在Angular 4中按条件使用不同的服务,如果是DEV环境,则使用testservice3,否则使用testservice: enter image description here

我的app.component.ts是这样的:

import { Component } from '@angular/core';
import { TestService } from './shared/test.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'DependencyInjectionNG';
  constructor (private testService: TestService) {
    this.testService.sayHello();
  }
}

我创建了一个test.service.ts:

import { Injectable } from '@angular/core';
import { LoggerService } from './logger.service';

@Injectable({
  providedIn: 'root',
  useFactory: xyzFactory,
  deps: [LoggerService, 'IS_DEV_ENV'],
  useValue: true
})

export class TestService {
  constructor() {}
  sayHello () {
    console.log('This is test service');
  }
}

export class TestService2 {
  sayHello() {
   console.log(`From TestService2 --> Hello`);
  }
}

export class TestService3 {
  constructor(public logService: LoggerService) {}
  sayHello() {
      this.logService.log('Message from logService');
      console.log(`From TestService3 --> Hello`);
  }
}

export function xyzFactory (logger: LoggerService, isDev: boolean) {
  console.log(isDev);
  if (isDev) {
    return new TestService3(logger);
  } else {
    return new TestService();
  }
}

logger.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LoggerService {

  constructor() { }

  log(message: string) {
    console.log(message);
  }
}

但是,我收到此错误:

错误TypeError:this.testService.sayHello不是函数     在新的AppComponent(app.component.ts:13

有人知道如何通过使用useFactory和useValue使用不同的服务吗?

非常感谢您!

0 个答案:

没有答案