使用Injection Token将字符串类型的参数注入到类的构造函数里

170 阅读1分钟

一个常见的错误消息:

error NG2003 - No suitable injection token for parameter

构造函数里有个参数类型为string:

  constructor(@Inject('apiUrl') private myname) {
    console.log('Jerry inject: ' + myname);
   }

这个myname通过注解@Inject修饰,id为apiUrl.

谁负责注入apiUrl呢?在app module里:

  providers: [{ provide: JerrySandBoxService },
  { provide: GreetingService, useClass: EnglishGreetingService},
  {
    provide: 'apiUrl',
    useValue: 'http://localhost:4200/heros'
  }],

运行时:

另一个例子:

const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
  providedIn: 'root',
  factory: () => {
    console.log('MyService factory called');
    return new MyService();
  }
});

构造函数:

constructor(private injectorJerry: Injector, private hostComponentService: HostComponentService, @Inject(TOKEN_HOST_CLASS_PROVIDER) h) {
    console.log('in HostDecoratorComponent, Host component service got from own Injector: ',
    hostComponentService, ' HostTokenComponentService: ', h);
    h.print();

    const BASE_URL = new InjectionToken<string>('只是描述');
    const injector =
    Injector.create({providers: [{provide: BASE_URL, useValue: 'http://localhost'}]});
    const url = injector.get(BASE_URL);
    console.log(url);

    const instance = injectorJerry.get(MY_SERVICE_TOKEN);
    console.log('MY SERVICE TOKEN: ', instance);
  }

要获取更多Jerry的原创文章,请关注公众号"汪子熙":