标签:
In order to resolve a dependency, Angular’s DI uses type annotations. To make sure these types are preserved when transpiled to ES5, TypeScript emits metadata. In this lesson we’ll explore how the @Injectable decorator ensures metadata generation for services that have their own dependencies.
For exmaple, the TodoService looks like this:
export class TodoService { todos = [ {id: 0, name: "eat"}, {id: 1, name: "sleep"}, {id: 2, name: "running"}, ]; getTodos(){ return this.todos; } }
Now we want to inject LoggerProvider into TodoService:
import {LoggerProvider} from ‘./LoggerProvider‘; export class TodoService { todos = [ {id: 0, name: "eat"}, {id: 1, name: "sleep"}, {id: 2, name: "running"}, ]; constructor(private logger: LoggerProvider){ } getTodos(){ this.logger.debug(‘Items‘, this.todos); return this.todos; } }
If we want to the code, it will show errors:
Cannot resolve paramster in TodoService
The problem for this is because, when TypeScript code compile to ES5 code, ‘LoggerProivder‘ is injected into the TodoService to decreator (Angular creates it).
We must provider decreator to the TodoService in order to let this class know how to handle DI. So to solve the problem, we just need to add ‘@Injectable‘ whcih provided by Angular:
import {LoggerProvider} from ‘./LoggerProvider‘; import {Injectable} from ‘@angular/core‘; @Injectable export class TodoService { todos = [ {id: 0, name: "eat"}, {id: 1, name: "sleep"}, {id: 2, name: "running"}, ]; constructor(private logger: LoggerProvider){ } getTodos(){ this.logger.debug(‘Items‘, this.todos); return this.todos; } }
[Angular 2] 8. Understanding @Injectable
标签:
原文地址:http://www.cnblogs.com/Answer1215/p/5877838.html