Issue
I want to delay the component's loading until the user's location is found. I defined a child routes. The project has a map and an information panel. The map and the information panel are working with latitude and longitude. I used leaflet map. I created a resolver but not working as I expected. Here, 'geo' is returning undefined. Where is the mistake?
HTML
<div class="container-fluid h-100">
<div class="row h-100">
<div class="col-lg-7">
<app-map></app-map>
</div>
<div class="col-lg-5 h-100">
<div class="tab-content">
<router-outlet></router-outlet>
</div>
</div>
</div>
</div>
ROUTE
export const appRoutes: Route[] = [
{
path: 'info', component: InfoComponent, resolve: {geo: GeolocationService}, children: [
{path: 'register', component: RegisterComponent},
{path: 'list', component: ListComponent}
]
}];
Geolocation service
export class GeolocationService implements Resolve<any> {
constructor() {
}
resolve(): Observable<any> {
return this.findLocation();
}
findLocation = () => {
let coords;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
if (position.coords) {
coords = {lat: position.coords.latitude, lng: position.coords.longitude};
return coords;
} else {
coords = {lat: 11, lng: 11};
return coords;
}
});
} else {
coords = {lat: 11, lng: 11};
return coords;
}
};
}
InfoComponent
export class InfoComponent implements OnInit {
constructor() {
}
ngOnInit(): void {
this.route.data.subscribe(data => {
console.log('data', data);
});
}
}
Solution
I would find it suspicious if the code even compiles. You should return a Promise from findLocation otherwise nothing will happen.
export class GeolocationService implements Resolve<any> {
resolve(): Promise<{lat: number, lng:number}> {
return new Promise((resolve,reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
if (position.coords) {
resolve({lat: position.coords.latitude, lng: position.coords.longitude});
} else {
reject(new Error('browser did not return coordinates'));
}
});
} else {
reject(new Error('browser does not support geolocation api'));
}
});
}
}
Answered By - sirrocco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.