2015-11-29 63 views
4

我试图在另一个使用的角2进样服务角2

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

DI注入一个服务。当我这样做,我得到这个错误:

无法解决所有参数CurrentBlog(?)。确保他们都有有效的类型或注释。

我已经用正常的组件测试过DI,它工作正常。 但是,当我注入服务。它根本不起作用。

回答

0

在这种情况下,只是DI是不够的。下面这个链接地址同样的问题:

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

所以它说:当emitDecoratorMetadata选项设置

打字稿生成的元数据。但是,这并不意味着它会为我们的代码的每个类或每个方法盲目地生成元数据。当装饰器实际附加到特定代码时,TypeScript仅为类,方法,属性或方法/构造器参数生成元数据。否则,会生成大量未使用的元数据代码,这不仅会影响文件大小,还会影响我们的应用程序运行时。

所以执行Metadta代,我们可以尝试将以下两个注释之一:

import {HttpService} from 'scripts/httpService'; 
import {Inject} from 'angular2/core'; 
export class CurrentBlog{ 

constructor(@Inject(HttpService) public httpService:HttpService){} 
} 

或者,

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

constructor(public httpService:HttpService){} 
} 
+0

这不是工作,因为那时Angular2会抱怨'为HttpService的没有提供!'。 – budhajeewa

+0

是的,这不会工作 –

1

在角2,你需要做的角度喷射器知道你的服务。为此,您需要将该服务标记为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){} 
}