【发布时间】:2017-04-12 16:06:33
【问题描述】:
我正在尝试使用 TypeScript 为我的 Angular 2 组件提供服务。我阅读了很多关于如何创建服务的教程,他们都说我的服务需要使用装饰器 @Injectable 并且我应该能够将它注入到我的组件中。当我想注入我的服务时,这似乎对我不起作用,但使用 @Inject 可以。
我的服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class GeolocationService {
/**
* Get the current location of the user
* @return {Observable<any>} An observable with the location of the user.
*/
public getLocation(): Observable<any> {
return Observable.create(observer => {
if (window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(position => {
observer.next(position);
observer.complete();
}, error => {
observer.error(error);
}, {
maximumAge: 0
});
} else {
observer.error('Browser does not support location services');
}
});
}
}
我的组件,不工作的版本 (v1):
import { GeolocationService } from './geolocation.service';
@Component({
templateUrl: 'home.component.html',
styleUrls: [ 'home.component.scss' ],
providers: [ GeolocationService ]
})
export class HomeComponent implements OnInit {
constructor(private myService: GeolocationService) {
this.myService.getLocation()
.subscribe(position => console.log('my position', position));
// .error(err => console.log('oop error', err))
}
}
我的组件,工作版本(v2)
import { GeolocationService } from './geolocation.service';
@Component({
templateUrl: 'home.component.html',
styleUrls: [ 'home.component.scss' ],
providers: [ GeolocationService ]
})
export class HomeComponent implements OnInit {
constructor(@Inject(GeolocationService) private myService: GeolocationService) {
this.myService.getLocation()
.subscribe(position => console.log('my position', position));
// .error(err => console.log('oop error', err))
}
}
你能解释一下为什么只有第二个版本有效吗?
【问题讨论】:
-
定义“不工作”。究竟会发生什么?你能在 plunkr 中重现它吗?
-
可能你的问题和stackoverflow.com/questions/39602890/…很相似
-
将其添加到您的模块中
-
能否请您添加您的 tsconfig 以及您在运行第一个版本时在控制台中看到的错误消息?请注意,当您的服务类本身没有任何要注入的依赖项时,不需要 @Injectable。要使服务可注入,您必须
provide它并在组件的constructor中具有正确的类型定义。我假设存在一些配置问题。
标签: angular typescript dependency-injection