The system was expecting a stream but received a value of 'undefined'

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.

Answer №1

I successfully resolved the issue at hand. The problem lies in the fact that the geocoder.geocode() function does not return a value, while the mergeMap() function expects a Promise, Observable, etc. Thus, geocoder.geocode() returned undefined. My solution involves wrapping this function with a Promise.

    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 => new Promise<any>((resolve, reject) => {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); 
                    console.log(longitude); 
                }                  
                resolve({location, longitude, latitude}(;
    })
            })).catch(error => {
                this.router.navigate(['/not-found'])
                return Observable.throw(error);
            })  
          }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Usage of Jasmine Testing for Subscribing to Observable Service in Angular's OnInit

Currently, I am facing challenges testing a component that contains a subscription within the ngOnInit method. While everything runs smoothly in the actual application environment, testing fails because the subscription object is not accessible. I have att ...

Using Typescript for-loop to extract information from a JSON array

I'm currently developing a project in Angular 8 that involves utilizing an API with a JSON Array. Here is a snippet of the data: "success":true, "data":{ "summary":{ "total":606, "confirmedCasesIndian":563, "con ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

AngularJS UI-Router in hybrid mode fails to recognize routes upon initial page load or reload

It appears that when using the @ui-router/angular-hybrid, routes registered within an ng2+ module are not being recognized during the initial load or reload. However, these same routes work fine when accessed by directly typing the URL. I have followed th ...

The property 'x' cannot be found on the data type 'true | Point'

I am dealing with a variable named ctx which can be either of type boolean or Point. Here is how Point is defined: type Point = { x: number y: number } In my React component, I have the following setup: const App = () => { const [ctx, toggleC ...

I'm baffled by how the community response is implemented in this particular TypeScript exercise on Exercism

I am currently learning TypeScript from scratch by working on exercises available on exercism Successfully completed the 5th exercise on Pangram. Below is my solution: class Pangram { alphabet = "abcdefghijklmnopqrstuvwxyz" constructor(privat ...

Create a TypeScript type that represents an empty collection

I recently acquired some knowledge about TypeScript through a university course I took this month. Is it possible for this to represent an empty set? type emptySet=0&1; Whenever I attempt to assign this to any value (for example: boolean, number, st ...

How to create an Ion-select element with dynamic options in Ionic 2?

Currently, I am working on an application in Ionic 2 and I am facing a challenge with adding ion-select options dynamically. Below is the snippet of my code: <ion-select [(ngModel)]="classifications" (ngModelChange)="updateSelectedValue($event)"> & ...

I am interested in adding a personalized icon to the progress bar in Material-UI

I am currently using the MUI linerProgressBar design. I would like to incorporate a custom UI Icon that moves along with the progress. Are there any examples of this available? I have searched for one in MUI but haven't found anything. If you know of ...

Struggling to identify the error while utilizing Jasmine's throwError function

I am relatively new to using Jasmine and have been experimenting with the toThrowError() function. However, I can't seem to get my test to pass successfully. In one of my functions, I purposely throw an error: test.service.ts test(list:{}){ if ...

Having trouble connecting my chosen color from the color picker

Currently, I am working on an angularJS typescript application where I am trying to retrieve a color from a color picker. While I am successfully obtaining the value from the color picker, I am facing difficulty in binding this color as a background to my ...

Trouble with Angular 7: Form field not displaying touched status

I am encountering an issue while trying to input data into a form, as it is not registering the touched status. Consequently, an error always occurs when attempting to send a message back to the user. In my TypeScript file, I am utilizing FormBuilder to c ...

The embedded component is throwing an error stating that the EventEmitter is not defined in

Currently, I am delving into the realm of angular and facing an issue. The problem lies in emitting an event from a component nested within the main component. Despite my efforts, an error persists. Below is a snippet of my code: import { Component, OnIn ...

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...

What is the best way to trigger a mat-menu to open with just one click, while also automatically closing any other open menus at

I've encountered an issue where if there are multiple menus in the header, opening a menu for the first time works fine. However, if a menu is already open and I try to open another one, it doesn't work as expected. It closes the previously opene ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

Efficiently storing a newly shuffled list of tasks into the db.json file using Angular

This is the content of my db.json document { "tasks": [ { "id": 1, "text": "Doctors Appointment", "day": "May 5th at 2:30pm", "reminder": true }, { ...

Set an interface to null within Angular 4

I've created an interface in Angular 4 called StatusDetail: interface StatusDetail { statusName: string, name: string } Next, I assigned some values to it within an Angular component: //Angular Component export class EditComponent implemen ...

Issue: Compilation error encountered when attempting to build module (from ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js):

I encountered an issue while trying to set up Angular Material. Initially, I received an error message. I attempted to resolve it by deleting the node modules and running npm i again, but the problem persists. How can I rectify this? Upon trying to launch ...