"An error occurred in Angular2 where the first index of the array

When I try to push the Google coordinates into an array, I am encountering some issues. Even though I have added the data, when I print console.log(this.markersData) it shows up as an empty array with objects-->[]

However, on the second click, I am able to get an array with an object like this [object]

https://i.sstatic.net/cd2R9.png

I also need access to the data from the first array. What could be causing this issue?

HTML

<button (click)="addPlace()" > </button>

Angular2 Function

import {Component, Input, OnInit, Output, EventEmitter, ElementRef} from '@angular/core';
import { Http, Headers, RequestOptions } from "@angular/http";
import { Observable } from 'rxjs/Rx';   

export class GoogleMapComponent  {

    markersData: any[] = [];

    addPlace(){
       this.http.get('https://maps.googleapis.com/maps/api/geocode/json?address=Rom').map((res: any) => res.json())
          .subscribe((res: any) => {
             // console.log(res.results[0].geometry.location);
             var geo = res.results[0].geometry.location;
                if(geo != undefined){
                   this.markersData.push(geo);  
                }
           }, 
           (error: any) => {
              console.log(error);
           });
        console.log(this.markersData);
    }

Answer №1

Upon reviewing your code, it appears that your console.log is located outside of your observable subscription, leaving it somewhat lost and disconnected from the completion of the request. This may be why it only works the second time.

I conducted a test using this plunker: http://plnkr.co/edit/qktCQKt9LLrzqogdkRho and everything seems to be functioning correctly in my evaluation.

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

Struggling to retrieve a particular value in Angular, but encountering difficulties

I am attempting to retrieve information from my Firestore Collection. Everything works fine when I print the JSON data, but I am encountering issues when trying to display a single value. In order to fetch the data, I have implemented the following code: ...

How can I create an endless animation using Angular6?

I created a 3D truck using HTML and CSS. The truck tires rotate 360 degrees if a variable (x) is true. If x is false, the rotation of the truck tires stops. This was achieved in CSS by setting the rotation to infinite. .wheel { animation: round 2s infi ...

Adding an item to a list using the PATCH method in Angular 7

Can anyone provide guidance on how to implement the PATCH method for manipulating an array within another array? ItemClass: export class ItemClass { constructor(public person: string, public name: string, public quantity: number, public price: number){} ...

Utilizing ngIf in a for loop in Angular 4

I'm currently exploring a method to render DOM elements conditionally using the ngIf directive. The condition is evaluated within a for loop utilizing the ngFor directive. To elaborate further, in my template I have the following structure: <div ...

Modify the "field" key type within the GridColDef interface of MUI DataGrid

Is there a way to assign an array of specific strings to the default type of GridColDef's field key, which is typically set to string? I attempted solutions like Array<Omit<GridColDef, 'field'> & {field: 'name' | &apo ...

Angular 4 Bootstrap dropdown issue - not functioning as expected

I am currently trying to use a Bootstrap dropdown list in conjunction with Angular 4, but I am encountering some issues. Despite having three items inside the "Varukorg", they are not displaying in line as expected. https://i.sstatic.net/zvgor.png <li ...

"I am experiencing an issue with the PrimeNG year picker as it is unable

My goal was to set up a simple PrimeNG calendar with just a year picker. I followed the implementation instructions from the documentation: <p-calendar inputId="year" [(ngModel)]="date1" view="year" dateFormat=" ...

Showing user's email post login in Angular 11

Currently, I am working on a project using Angular 11 and .NET Core with web API JWT token authentication to handle user Login functionality. I have successfully implemented the user login feature, which redirects users to the dashboard upon successful aut ...

Is it possible for Angular components to retrieve information on the current route and parameters?

I am struggling to understand why it's so difficult... why we are not supposed to care about the route from outside the routed component.... HOWEVER: I am attempting to develop a service so that my header (and any other component) can have access to ...

Angular date control and its corresponding date panel are not properly aligned on the user interface

I am utilizing Angular and Angular Material for date control display. See the code snippet below: <input type="date" (change)="validateDateRange($event,true, index)" class="form-control oot-start-date align-middle" name=& ...

Service injection results in an error

I am encountering an issue while trying to inject a service into a component, and the error message I receive is as follows: EXCEPTION: TypeError: Cannot read property 'getDemoString' of undefined It appears that the service is not being prop ...

Send Components to another component without specific TypeScript typespecified

Struggling with a situation where I am faced with the challenge of working around strongly typed variables. The issue arises with a set of icons as components and an icon wrapper component. The wrapper component requires a themeMode variable to determine ...

Avoid creating a pyramid structure by connecting multiple observables only after ensuring that each one is fully completed

Utilizing rxjs, I am wondering if there is a way to trigger the next function only when the observable has completed. Rather than the nested structure below: this.Start(data).subscribe( (data) => { console.log('next'); }, ...

The provided Material-UI Fade component contains multiple children, which is not supported by 'ReactElement<any, any> | undefined'

I'm struggling to implement a Material UI <Fade> component in my code. Unfortunately, I keep encountering the following error message and as someone who is still learning TypeScript, I am unsure of how to resolve it. Error: Expected ReactElement ...

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

Optimizing media queries with Angular: A comprehensive guide

I am currently using NgZone to handle media queries in my Angular project. I am curious if there is a more efficient way to achieve this. import { NgZone } from '@angular/core'; const SMALL_WIDTH_BREAKPOINT = 840; export class AppComponent im ...

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

Can we store an API response in cache to access the API without an internet connection?

Is there a way to cache the master date API so that even when offline, the response can still be accessed? ...

Is it possible to multitask within a structural directive by performing two actions simultaneously?

I want to develop a custom structural directive with the following behavior: <p *myDirective="condition">This is some text</p> If condition is false, the <p> tag will not be displayed at all. If condition is true, the <p> tag wi ...