将服务注入组件
Inject a service into a component
仅供参考:使用 angular2 (2.0.0-alpha.45) 和 TypeScript (1.6.2)
正在尝试创建一个简单的服务以注入组件。
我遇到的错误:
Cannot resolve all parameters for {ComponentName}(?). Make sure they all have valid type or annotations.
引导:
bootstrap(App, [ROUTER_PROVIDERS, HTTP_PROVIDERS]);
服务(我的-service.ts):
import {Injectable} from 'angular2/angular2';
@Injectable()
export class MyService {
public doSomething() {}
}
消费组件:
import {Component} from 'angular2/angular2';
import {MyService} from './my-service';
export class ListManager{
constructor(private myService: MyService){
console.log('myService', myService);
}
}
Things I've tried
- 在服务中:
- marking/un-marking
@Injectable
的服务
- 在引导过程中:
- Adding/removing
MyService
进入提供商的引导列表
- 在组件中
- 将服务指定为提供者
@Component({providers: [MyService]})
- 将服务指定为绑定
@Component({bindings: [MyService]})
我想你会这样做:
constructor(private myService: MyService){
console.log('myService', myService);
}
您还必须在@Component 定义中将服务指定为提供者
@Component({
...
providers: [MyService]})
尝试在您的组件中执行此操作:
import {Component} from 'angular2/angular2';
import {Inject} from 'angular2/core';
import {MyService} from './my-service';
export class ListManager{
private listService: ListService;
constructor(@Inject(ListService) listService: ListService){
console.log('listService', listService);
}
}
(注意构造函数里面的new import和@Inject
)
让我知道它是否适合您。 plunker 也有助于隔离问题。
仅供参考:使用 angular2 (2.0.0-alpha.45) 和 TypeScript (1.6.2)
正在尝试创建一个简单的服务以注入组件。
我遇到的错误:
Cannot resolve all parameters for {ComponentName}(?). Make sure they all have valid type or annotations.
引导:
bootstrap(App, [ROUTER_PROVIDERS, HTTP_PROVIDERS]);
服务(我的-service.ts):
import {Injectable} from 'angular2/angular2';
@Injectable()
export class MyService {
public doSomething() {}
}
消费组件:
import {Component} from 'angular2/angular2';
import {MyService} from './my-service';
export class ListManager{
constructor(private myService: MyService){
console.log('myService', myService);
}
}
Things I've tried
- 在服务中:
- marking/un-marking
@Injectable
的服务
- marking/un-marking
- 在引导过程中:
- Adding/removing
MyService
进入提供商的引导列表
- Adding/removing
- 在组件中
- 将服务指定为提供者
@Component({providers: [MyService]})
- 将服务指定为绑定
@Component({bindings: [MyService]})
- 将服务指定为提供者
我想你会这样做:
constructor(private myService: MyService){
console.log('myService', myService);
}
您还必须在@Component 定义中将服务指定为提供者
@Component({
...
providers: [MyService]})
尝试在您的组件中执行此操作:
import {Component} from 'angular2/angular2';
import {Inject} from 'angular2/core';
import {MyService} from './my-service';
export class ListManager{
private listService: ListService;
constructor(@Inject(ListService) listService: ListService){
console.log('listService', listService);
}
}
(注意构造函数里面的new import和@Inject
)
让我知道它是否适合您。 plunker 也有助于隔离问题。