I am trying to make a service for my Angular 2 component with TypeScript. I read a lot of tutorials on how to create a service and all of them said that my service needs to use the decorator @Injectable and that I should just be able to inject it in my component. This does not seem to be working for me when I want to inject my service, but using @Inject does.
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');
}
});
}
}
My component, version that is not working (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))
}
}
My component, working version (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))
}
}
Can you please explain to me why only the second version works?