Angular 2 “No provider for String!”

余生颓废 提交于 2019-12-06 06:00:32

You can't just inject arbitrary things. Anything you try to inject, needs to be configured to be injectable. In most cases that means just adding the class to the providers list. In the case of a string, it's not that simple. We need to do a few things.

  1. First we need to create a token1
  2. Then configure the string to be injected, using that token.
  3. Then with the same token, @Inject it into the target.

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

// 1. Create token
export const ACTION = new OpaqueToken('app.action');

// 2. Configure the `providers` (Maybe in the AppModule)
providers: [
  { provide: ACTION, useValue: 'the value you want'
]

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

export class DataService {
  // 3. Injection target 
  constructor(@Inject(ACTION) action: string) {}
}

1 - See Dependency Injection Tokens


UPDATE

Now, with Angular 4, we should use InjectionToken rather than OpaqueToken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!