After researching how to create a service for my Angular 2 component with TypeScript, I found that most tutorials recommend using the @Injectable decorator. However, when I tried to inject my service into my component, it didn't work as expected. Surprisingly, using @Inject seemed to do the trick.
This is the code for my service:
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');
}
});
}
}
Here is the initial version of my component that did not work (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))
}
}
And here is the updated working version of my component (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))
}
}
If anyone can explain why only the second version worked correctly, I would greatly appreciate it.