我正在尝试使用TypeScript为我的Angular 2组件提供服务。我阅读了很多关于如何创建服务的教程,并且他们都说我的服务需要使用装饰器@Injectable,并且我应该能够将其注入到组件中。当我想注入我的服务时,这似乎不适用于我,但使用@Inject。Angular 2 @Injectable似乎没有工作
我的服务:
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中重现吗? –
可能你的问题非常类似于http://stackoverflow.com/questions/39602890/angularjs-2-0-cant-inject-anything-through-component-constructor – yurzui
将它添加到你的模块 – chabeee