【发布时间】:2016-08-07 16:44:37
【问题描述】:
我在 Angular 2 中编写了两项服务。其中一项是 Http 的基本自定义类,其中包含一些自定义功能(目前看起来很基础,但会不断扩展):
ServerComms.ts
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
@Injectable()
export class ServerComms {
private url = 'myservice.com/service/';
constructor (public http: Http) {
// do nothing
}
get(options) {
var req = http.get('https://' + options.name + url);
if (options.timout) {
req.timeout(options.timeout);
}
return req;
}
}
另一个类TicketService利用上面的这个类,并调用服务中的一个方法。这定义如下:
TicketService.ts
import {Injectable} from 'angular2/core';
import {ServerComms} from './ServerComms';
@Injectable()
export class TicketService {
constructor (private serverComms: ServerComms) {
// do nothing
}
getTickets() {
serverComms.get({
name: 'mycompany',
timeout: 15000
})
.subscribe(data => console.log(data));
}
}
但是,每当我尝试此操作时,都会收到以下错误:
"No provider for ServerComms! (App -> TicketService -> ServerComms)"
我不明白为什么?当然,我不需要注入其他服务所依赖的每项服务吗?这会变得相当乏味吗?这在 Angular 1.x 中是可以实现的——我如何在 Angular 2 中实现同样的目标?
这是正确的做法吗?
【问题讨论】:
标签: javascript dependency-injection dependencies angular