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

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Need help with TypeScript syntax for concatenating strings?

Can you explain the functionality of this TypeScript syntax? export interface Config { readonly name: string readonly buildPath: (data?: Data) => string readonly group: string } export interface Data { id: number account: string group: 'a&a ...

Conditional return type mistakes

I'm facing an issue with a function that takes a parameter "value" and is supposed to return 0 or 1 based on its true or false value. Check it out here. const f = <T extends boolean>(value: T): false extends T ? 0 : 1 => { if (value === ...

Strategies for modifying the bound value in Angular with an observable object

I am attempting to convert the offset value for a time object in the URI, which is stored in an observable object. The issue I am encountering is: ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checke ...

Is it possible that React useState is not allowing a default value to be set in this case?

In my chart component, I have the functionality to show/hide specific lines. To keep track of active lines, I maintain an array called activeKeys in a state. Initially, I populate this array by calling a function named getKeys, which takes an array of data ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

Implementing chance.js in an Angular 4.x Component's ngOnInit() Method

I just started using angular 4.x and I'm trying to load change.js in the ngOnInit() function. I've attempted a few things but nothing seems to be working. Here is the code snippet: This is the code I have so far: import { Component, OnInit, In ...

Child component not receiving disabled state from Angular 8 FormControl

In my code, there is a unique custom input that I have defined: <nivel-servico-slider formControlName="fornecedor_a"></nivel-servico-slider> This custom input has all the necessary properties as outlined in Angular's guide for c ...

Get React-table TS up and running on your local machine using VS Code

Objective: I am trying to get React-table working with TypeScript on my local computer. Challenge: The code is based on this page https://codesandbox.io/s/gkzg3?file=/src/makeData.ts However, when I attempt to apply the code on my local computer, I ...

Tips for updating the font size of your MUI Accordion title

I was attempting to adjust the font size of the MUI-5 Accordion title. It seems like I need to override it, but I am unsure about how to do so with CSS in MUI-5. Instead of 'SX', it uses 'htmlSx'. When I tried using it, it did not produ ...

Guide to showcasing an image obtained from a Web API in Angular

I have a unique challenge with displaying images on the user interface. The image data is retrieved from a database through a web API, and the image path is stored in the DB's imagePath column. However, when fetching the data via the web API, only the ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

getting requestParam of type date from angular using spring

Hello everyone, I am new to working with Angular and Spring. I am attempting to send a GET request with some date parameters, but I keep encountering an error. Here is the HTML code snippet: <div class="form-row"> <div c ...

Having trouble with running the command ng update -g @angular/cli, receiving an error message

When running the command ng update -g @angular/cli I encountered the following issue: Unexpectedly, an error occurred stating package amcharts3-angular2 has no version null while trying to execute the ng update -g @angular/cli command. ...

Tips for monitoring a function (from a different component) within the mat-datepicker:

I have implemented the mat-datepicker in the component: html: <input [(ngModel)]="date.from" [matDatepicker]="picker" [value]="fDate.value" formControlName="dateFrom" id="dateFrom" matInput name="dateFrom" required > <mat-date ...

The button fails to log any text to the developer console

Attempting to verify the functionality of my button by logging a message on the developer console. However, upon clicking the button, the text does not appear in the console. import { Component, EventEmitter, Input, Output } from '@angular/core'; ...

The React Nested Loop Query: Maximizing Efficiency in Data

Learning React has been a challenge for me, especially when comparing it to XML/XPath. In this scenario, I have two arrays simplified with basic string properties... customerList: Customer[] export class Customer { id: string = ""; firstnam ...