I'm learning Angular 2. I'm using a LocationService with an Observable that hands me the coordinates after some time. This is my code.
location.service.ts
public getLocation(): Observable<any> {
return Observable.create(observer => {
if(window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
(position) => {
observer.next(position);
observerplete();
},
(error) => observer.error(error)
);
} else {
observer.error('Unsupported Browser');
}
});
}
appponent.ts
ngOnInit() {
this.location.getLocation().subscribe((coordinates) => {
this.lat = coordinates.coords.latitude;
this.lng = coordinates.coords.longitude;
});
}
How can I subscribe to the receiving of the coordinates so I can render a map, add a marker, .. once I receive them from the first subscribe.
I'm learning Angular 2. I'm using a LocationService with an Observable that hands me the coordinates after some time. This is my code.
location.service.ts
public getLocation(): Observable<any> {
return Observable.create(observer => {
if(window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
(position) => {
observer.next(position);
observer.plete();
},
(error) => observer.error(error)
);
} else {
observer.error('Unsupported Browser');
}
});
}
app.ponent.ts
ngOnInit() {
this.location.getLocation().subscribe((coordinates) => {
this.lat = coordinates.coords.latitude;
this.lng = coordinates.coords.longitude;
});
}
Share Improve this question edited Feb 27, 2017 at 21:13 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Feb 27, 2017 at 20:58 Miguel StevensMiguel Stevens 9,24019 gold badges75 silver badges136 bronze badgesHow can I subscribe to the receiving of the coordinates so I can render a map, add a marker, .. once I receive them from the first subscribe.
1 Answer
Reset to default 11Firstly, I would put that method into a service.
So say you have a file called location.service.ts
with the export class LocationService
inside this file you'll have the following
getLocation(): Observable<any> {
return Observable.create(observer => {
if(window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
(position) => {
observer.next(position);
observer.plete();
},
(error) => observer.error(error)
);
} else {
observer.error('Unsupported Browser');
}
});
}
Inside your ponent you'll do something like this:
import { Component, OnInit } from '@angular/core';
import { LocationService } from '/shared/location.service.ts';
@Component({
selector: 'app-root',
templateUrl: './app.ponent.html',
styleUrls: ['./app.ponent.css']
})
export class AppComponent implments OnInit {
constructor(private service: LocationService) {}
ngOnInit(){
this.service.getLocation().subscribe(rep => {
// do something with Rep, Rep will have the data you desire.
});
}
}