zoukankan      html  css  js  c++  java
  • [Angular 2] Understanding @Injectable

    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;
        }
    }
  • 相关阅读:
    结对项目之感
    调查问卷之体会
    我的软件工程课程目标
    关于软件工程的课程建议
    结对编程--fault,error,failure
    结对编程总结
    结对编码感想
    我的软件工程课目标
    《软件工程》课之-调查问卷的心得体会
    软件工程课程讨论记录
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5877838.html
Copyright © 2011-2022 走看看