Obtain the data from a service that utilizes observables in conjunction with the Angular Google Maps API

In my Angular project, I needed to include a map component. I integrated the Google Maps API service in a file called map.service.ts. My goal was to draw circles (polygons) on the map and send values to the backend. To achieve this, I added event listeners such as circlecomplete and radius_changed in my services.

 public initMap(mapElement: ElementRef, search: ElementRef, options: MapOptions) {
    return this.init().pipe(
      switchMap(() =>
        this.createGoogleMap(mapElement.nativeElement, search.nativeElement, options)
      ),
      exhaustMap(() =>
        forkJoin(
          this.subscribeToDrawingEvents('circlecomplete').pipe(
            map(d => console.log(d))
            ),
          this.subscribeToCenterChangeEvents('center_changed').pipe(
              map(d => console.log(d))
              ),
          this.subscribeToRadiusChangeEvents('radius_changed').pipe(
                map(d => console.log(d))
                ),
          this.subscribeToSearchboxEvents('places_changed')
        )
      )
    );
  } 

In the initMap method, I created the JavaScript code and appended it to the component. Then, createGoogleMap function is used to generate the map, followed by adding event listeners. This service is then subscribed to from a map.component.ts.

ngOnInit() {
    this.option = {
      center: this.center ? this.center : { lat: 0, lng: 0 },
      zoom: this.zoom ? this.zoom : 4,
      markers: this.markers ? this.markers : []
    };
    this.subscribe_event$ = this.service.initMap(this.googleMap, this.searchInput, this.option);
    this.subscribe_event$.subscribe();
  } // ngOnInit()

I successfully received values during the center change event:

 this.subscribeToCenterChangeEvents('center_changed').pipe(
          map(d => console.log(d))
          ),

However, I faced issues when trying to get values into the subscribing component. Here is how I set up the observer:

private subscribeToCenterChangeEvents<E>(eventName: string): Observable<any> {
    console.log('Circle Center Change listener added');
    return Observable.create((observer: Observer<any>) => {
      google.maps.event.addListener(this.drawingManager, eventName, drwnCircle => {
        const circle_radius: Number = drwnCircle.getRadius();
        const circle_center: LatLng = drwnCircle.getCenter();
        console.log(circle_radius);
        observer.next({ drawn_circle: circle_radius });
      });
    });
  } // subscribeToCenterChangeEvents

Answer №1

When you're in the subscribe method, make sure to store the values in a variable.

resultValues: your_Type;
this.subscribeEvent$.subscribe((responseData) => {
    this.resultValues = responseData; 
});

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

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Strategies for Patience: Juggling Multiple Requests

Trying to determine the most efficient way to handle multiple requests simultaneously without waiting for each other. // table filling public SUB_getActSearch: Subscription; // table filling 2 public SUB_getDeclarationSearch: Subscription; public fillTa ...

Navigating focus within form elements using Angular techniques

Purpose There is a form with various input elements (el1, el2 ...) el1 may or may not have initial focus when a keydown event occurs, the following actions should be taken: If none of the input elements are in focus, move focus to the first non-empty e ...

Encoding and Decoding Base64 in Nativescript Using Angular 2

I've searched high and low for a solution but I can't seem to find one. Even after attempting to utilize atob() and btoa(), my efforts were futile. It seems that despite what intellisense suggests, these methods cannot be used. Additionally, plug ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

ViewContainerRef fails to render component on the DOM

@Component({ selector: 'my-cmp', template: ` <div #target></div> ` }) export class MyCmp { @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef; render() { let component = createComponent(met ...

What is the reason that the command `npx create-react-app my-app --typescript` is not providing me with the expected TypeScript files?

I used the command npx create-react-app my-app --typescript to create my React project, but it seems like I still ended up with the default JavaScript boilerplate files. I was expecting to see files with a .tsx or .ts extension and use import * from as R ...

Issue TS2322 states that the type 'Observable<{} | T>' cannot be assigned to type 'Observable<T>'

Recently, I came across a useful example of error handling with the async pipe in Angular on this website: However, when attempting to implement it in Angular 7, I encountered compilation errors. readonly data$: Observable<T>; constructor(data: ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Exploring Local Gems with Google Places API in Ionic 2

I recently integrated the Google Maps API into my app and now I am looking to incorporate Google Places as well. I have managed to successfully implement Geolocation, but I am facing difficulties when trying to perform a nearby search for "supermarkets" in ...

Is there a way to ensure that in React (Typescript), if a component receives one prop, it must also receive another prop?

For instance, consider a component that accepts the following props via an interface: interface InputProps { error?: boolean; errorText?: string; } const Input = ({error, errorText}: InputProps) => { etc etc } How can I ensure that when this com ...

Varied Data Transfer Objects used for requests and responses

Currently, I am dealing with MongoDB and subdocuments. MongoDB automatically adds extra fields that cannot be specified in a POST request; they can only be retrieved using a GET request. To put it simply: different data transfer objects (dtos). I am utili ...

How to eliminate a particular validator from a form group in Angular

My goal is to eliminate the specific validator from the validator array so that I can reconfigure the controls when certain values have changed. I am aware of the traditional solution where I would need to repeatedly set validators. checked(event: MatC ...

The error message "The element 'router-outlet' is unrecognized during the execution of ng build --prod" appears

I encountered a specific error message when running ng build --prod, although the regular ng build command works without issue. Error: src/app/app.component.html:1:1 - error NG8001: 'router-outlet' is not recognized as an element: 1. If 'rou ...

Whenever I try to load the page and access the p-tableHeaderCheckbox in Angular (primeng), the checkbox appears to be disabled and I am unable to

I attempted to use the disabled attribute on p-tableheadercheckbox in order to activate the checkbox. <p-tableHeaderCheckbox [disabled]="false"></p-tableHeaderCheckbox> <ng-template pTemplate="header"> <tr> ...

Issue encountered when attempting to convert Angular application to Angular Universal

While attempting to convert my Angular App into Angular Universal, I encountered an issue. I used the command "ng add @nguniversal/express-engine --clientProject my-app" An error occurred: Module not found - '@schematics/angular/utility/json-file&apo ...

Passing data to a child component using Context in React is not working

I have a parent component where I am storing data in an array of objects and then passing it to another component through Context. Here is how my parent component looks: export type HistoryData = { input: string; date: string; ...