码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular 2] 8. Understanding @Injectable

时间:2016-09-17 07:09:37      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!