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;
        }
    }
  • 相关阅读:
    Nginx启动/停止服务和各种命令
    文件权限导致Weblogic Embedded LDAP Server启动失败解决办法
    jmeter(八)非图形界面、输出html报告
    jmeter(七)服务器监控
    python中如何把一段文字中的空格替换成换行符
    jmeter(五)jpgc插件的使用
    jmeter(四)提取响应结果
    Jmeter (三)变量、参数化、函数
    jmeter(二)录制脚本
    Jmeter(一)发送http请求
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5877838.html
Copyright © 2011-2022 走看看