Inject services in another service angular 2

前端 未结 2 1196
粉色の甜心
粉色の甜心 2021-01-13 08:32

I tried injecting one service in another using DI of angular 2

import {HttpService} from \'scripts/httpService\';
export class CurrentBlog{
    constructor(         


        
2条回答
  •  执笔经年
    2021-01-13 09:07

    In this case just DI won't be enough. This link below addresses the same problem :

    http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

    So it says :

    TypeScript generates metadata when the emitDecoratorMetadata option is set. However, that doesn’t mean that it generates metadata blindly for each and every class or method of our code. TypeScript only generates metadata for a class, method, property or method/constructor parameter when a decorator is actually attached to that particular code. Otherwise, a huge amount of unused metadata code would be generated, which not only affects file size, but it’d also have an impact on our application runtime.

    So to enforce Metadta Generations we can try putting either of the following two annotations :

    import {HttpService} from 'scripts/httpService';
    import {Inject} from 'angular2/core';
    export class CurrentBlog{
    
    constructor(@Inject(HttpService) public httpService:HttpService){}
    }
    

    Or,

    import {Injectable} from 'angular2/core';
    import {HttpService} from 'scripts/httpService';
    @Injectable()
    export class CurrentBlog{
    
    constructor(public httpService:HttpService){}
    }
    

提交回复
热议问题