问题描述
我有三类:
@Injectable()
export class ApiService {
constructor(public http: Http) {}
get(url: string) {
return http.get(url);
}
}
@Injectable()
export abstract class BaseService {
constructor(protected serv: ApiService) {}
}
@Injectable()
export class MediaService extends BaseService {
// Why do we need this?
constructor(s: ApiService) {
super(s)
}
makeCall() {
this.serv.get("http://www.example.com/get_data")
}
}
在Angular2我必须包括BaseService的两者的构造和的MediaService即使MediaService继承BaseService。
In Angular2 I have to include for both the constructor of BaseService and MediaService even though MediaService inherits the BaseService.
我如何能得到Angular2注入BaseService无MediaService的构造方法有吗?
How can I get Angular2 injection into the BaseService without having it in the constructor of MediaService?
现在我都延长取决于ApiService而他们从BaseService继承BaseService类。
Now I have all the classes extending the BaseService depending on the ApiService while they inherit from the BaseService.
推荐答案
我认为这是不是支持。它在Angular2,即方法依赖注入工作的基础上的装饰。后者的使用相关联的类的构造函数,以确定哪些必须注射。你必须知道类的概念,并延伸都是本机由打字稿,但这样的code支持的transpiled成JavaScript。
I think that it's not something supported. It's the way dependency injection works in Angular2, i.e. based on decorators. The latters uses the constructor of the associated class to determine what must be injected. You must be aware that the concept of class and extends are natively supported by TypeScript but such code is transpiled into JavaScript.
看到这个答案,了解有关transpiled code更多详细信息:
See this answer for more details about the transpiled code:
- How to inject service to class and then extend component with it?
希望它可以帮助你,
蒂埃里
Hope it helps you,Thierry
这篇关于Angular2访问全球服务,而不包括它在每一个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!