Home > Software design >  Unable to get data from service using the Observable in first click
Unable to get data from service using the Observable in first click

Time:01-05

I'm working on a function to get a string value from the service that I create.

googlemap.service.ts

enter image description here

app.component.ts

enter image description here

I'm trying to get the duration but the result ended up like this, It need me to click twice so that I able get the expected result.

result

enter image description here

How should I get the result just in one click.

UPDATE

enter image description here

CodePudding user response:

There are multiple issues with the code:

  • The observable returned from setTravelDuration is a synchronous one, and not asynchronous. Even before directionService.route executes the callback, you have already returned an observable that executes immediately on subscribe.
  • The console.log('duration on map ...') will execute synchronously and doesn't take into account the code written within subscribe.

For 2nd point you can simply move the console.log within subscribe i.e after console.log('x', x).

For 1st point you can write the code as below:

    // within setTravelDuration method
    const directionServicePromise = new Promise<string>((resolve, reject) => {
      directionService.route({
        origin: origin,
        // Remaining options
      }, (res, status) => {
        if (status === 'OK') {
          // Perform some logic
          // ...
          const text = data?.duration!.text || '';
          resolve(text) // provide the value as per your use case
        } else {
          // resolve or reject as per your use case
        }
      });
    });
    
    return from(directionServicePromise);

CodePudding user response:

It doesn't work the second time because you have to click twice, it works because by the time you click the second time, you got the response for the first request meanwhile and this.travelDuration is now initialized.

The real issue is the console.log is outside of the subscribe callback. You are trying to get synchronous data from an asynchronous code.

By subscribing to an async observable, it means the callback will be called when you'll get the response from your request.

As you can see, the console.log(x, x)is displayed in your console between the two clicks:

  • clicked the first time
  • a request is sent
  • the second console.log is called (undefined)
  • the response is received
  • the inner console.log is called (initialized)
  •  Tags:  
  • Related