I've been attempting to make chained http requests using Rxjs, but encountering a frustrating error...
Error: Uncaught (in promise): TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
My goal is to retrieve the location object from my API, and then extract the latitude and longitude based on location.address
.
declare const require : any;
@Injectable()
export class GoogleMapLocationResolver implements Resolve<{location: Location, longitude: number, latitude: number }> {
constructor( private locationService: LocationService,
private route: ActivatedRoute,
private router: Router){}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): {location: Location, longitude: number, latitude: number } | Observable<{location: Location, longitude:number, latitude: number }> | Promise<{location: Location, longitude: number, latitude: number }> {
let geocoder = require('geocoder');
return this.locationService.getLocation(route.params['id']).map(
(response: Response)=> { return response.json() }
).mergeMap(location => geocoder.geocode(location.address, function(err, data){
let latitude
let longitude
if(data.status === 'OK'){
console.log('Status ok: ')
console.log(data)
let results = data.results;
latitude = results[0].geometry.location.lat;
longitude = results[0].geometry.location.lng;
console.log(latitude); // PRINTS CORRECT
console.log(longitude); // PRINTS CORRECT
}
return {location, longitude, latitude};
})).catch(error => {
this.router.navigate(['/not-found'])
return Observable.throw(error);
})
}
}
NOTE:What's peculiar is that despite the error, the console prints the latitude and longitude correctly! ('// PRINTS CORRECT' comment)
EDIT: Yes, my mistake was declaring variables within the if statement, but surprisingly that did not cause the issue in the end. I'll post the solution shortly.