Я пытаюсь сделать сервис для моего компонента Angular 2 с помощью TypeScript. Я прочитал много учебников о том, как создать службу, и все из них сказали, что мой сервис должен использовать декоратор @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