简体   繁体   中英

Inject services in another service angular 2

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

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

When I do this, I get this error :

Cannot resolve all parameters for CurrentBlog(?). Make sure they all have valid type or annotations.

I have tested DI with normal components and it works fine. But when I inject it in service. It simply doesn't work.

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){}
}

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){}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM