はじめてのAngular2/Injectableを作る・利用する
Injectableってなに
Angular2でDIするときのinjectする要素。
Injectableを作る
- @Injectable(デコレータ)をつけて(多段Injectでなければ要らない?→そうみたいです※)
@Injectable()
- classをexportする
export class MyService{
loadData(): string[] {
return ['hoge', 'moge', 'fuga'];
}
}
@Injectableというデコレータを書くだけです。
オフィシャルでは、今は要らなくてもとりあえず書いておく、のがベストプラクティスだと言っています。
The HeroService doesn’t have any dependencies at the moment. Add the decorator anyway. It is a “best practice” to apply the @Injectable() decorator from the start both for consistency and for future-proofing.
Injectableを利用(Inject)する
- exportしたクラスをimportして
import {MyService} from './my.service';
- メタデータのprividersに追加して
@Component({
...
providers: [MyService]
})
- constructorの引数にする
export class AppComponent{
private list: string[];
constructor(private myService: MyService) {
this.list = myService.loadData();
}
}
コンストラクタの引数にするだけでDIされますが、この記述はInjectを省略しているだけのようです。また、providersにProviderを与えずにMyServiceを与えているのも省略した書き方です(参考記事を見てね)。
ソースコード
参考
作成日 2016-07-14
