Inject services in another service angular 2

前端 未结 2 1197
粉色の甜心
粉色の甜心 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){}
    }
    
    0 讨论(0)
  • 2021-01-13 09:08

    In angular 2 you need to make the angular injector aware of your service. To do this you need to mark the service as Injectable.

    HttpService

    import {Injectable} from 'angular2/angular2';
    
    @Injectable()
    export class HttpService{
        ...
    }
    

    CurrentBlog

    import {HttpService} from 'scripts/httpService';
    import {Inject} from 'angular2/core';
    
    export class CurrentBlog{
    
        constructor(public httpService:HttpService){}
    }
    
    0 讨论(0)
提交回复
热议问题