Exploring the Depths of Angular 4 - Understanding Observables

In my code, I have a function where I need to assign a specific value returned from an HTTP service to a member variable.

calculateDistance() {
for (var ix=0; ix<this.rps.length; ix++) {
  this.googleService._distanceBetween(this.myLatLng, this.rps[ix].latLng)
  .subscribe(response => {
    this.resp = <GeoResponse>response;
    this.rps[ix].distFromMe = this.resp.distance.toString();
  });
}

}

The issue I'm facing is that I can't access the array named rps within the observable.

Is there a different way to solve this problem?

Answer №1

The problem arises from the declaration of the forLoop index 'ix' using 'var'. Since it is declared with 'var', its scope is maintained and the value of 'ix' will be (this.rps.length + 1) when the callback to subscribe is executed. For example, if the array length is 5, the value of ix will be 6 at the time of the callback. This results in an error because this.rps[ix] is undefined. To fix this issue, adjust the forLoop like so:

for (var ix=0; ix<this.rps.length; ix++) {
//create an inner function to keep the closure for ix;
  ((index: number) => {
    this.googleService._distanceBetween(this.myLatLng, this.rps[index].latLng)
    .subscribe(response => {
      this.resp = <GeoResponse>response;
      this.rps[index].distFromMe = this.resp.distance.toString();
    });
  })(ix); // calls the created function
}

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

Accessing URLs directly with the Angular 2 Router

I currently have a file named main.component.ts with the following code: It can be found in: root/ import {Component, OnInit, OnChanges, IterableDiffers} from 'angular2/core'; import {TypeService} from './type/type.service'; import { ...

Establishing fixed values in an angular2 component

Is it possible in angular 2 to initialize values within the HTML view of a component that has already been rendered in PHP? //html page: <dropdown [(options)]="['Available', 'Busy', 'Away', 'Offline']"></dr ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Having difficulty retrieving a JSON Object value through an angular2 pipe

I am currently working on creating a dynamic table using Angular2. I have set up an Angular2 component with two pipes: the first pipe successfully retrieves the key from the JSON object, which is used as the column for the table. However, the second pipe, ...

Node.js backpressure with RXJS and PostgreSQL

New title: How can I manage the speed of PgSQL results streaming in JavaScript? Running into memory problems with nodejs v4.5.0 using RXJS(5.4.0) and PostgreSQL (driver "pg": "6.1.4"). I've taken matters into my own hands by manually creating an obs ...

Using untyped JavaScript NPM modules in TypeScript for node: A beginner's guide

Recently, I delved into TypeScript and found myself working on a project with the following structure: -src | index.ts | MyClass.ts -node_modules -npm_js_module | index.js | utils.js - src | someModuleFile.js | someModuleFile2.js I am trying to u ...

Displaying Images in Bootstrap 4 Grid with Angular 7 Conditional Rendering

Currently, I have a display grid set up using Bootstrap 4's card feature. I am looking to iterate through an array of images and only display the images that match a specific status. When I include the *ngIf='image.status == sTab.status' c ...

Unable to showcase a dynamic image using [style.background-image] in Angular 7

I am encountering an issue in my Angular application where I am unable to load background images dynamically from my backend. Displaying regular pictures is not a problem for me. However, the background images are not loading and I do not receive any err ...

Why does the name not appear when I first click the button, only 'emit'?

I am attempting to utilize eventemiter in order to send a name when clicking a button, but it doesn't seem to be working as expected. The issue I am facing is that the name is not displayed the first time I click the button, however, if I click it aga ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

Unable to access the inner object using key-value pair in Angular when working with Firebase

Within my json object, there is an inner object labeled data, containing {count: 9, message: "9 sites synced"} as its contents - also in json format. My objective is to extract the value from message, rather than count. Provided below is the temp ...

Exploring the utilization of async and await within NGRX effect in Angular

My current project involves working with NGRX for State Management in Angular 11. On component load, I am displaying a list of tenants. To achieve this, I'm utilizing NGRX effects to make an HTTP request through a service. This is the NGRX effect im ...

Jest unit tests are failing due to an error stating that VUE_APP_CONFIG is not defined

export interface VueAppSettings { BASE_URL: string; BASE_URL_V2: string; } declare const VUE_APP_SETTINGS: VueAppSettings; export const APP_SETTINGS = { ...VUE_APP_SETTINGS } as const; I am encountering a reference error in the code snippet abov ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

The art of connecting Angular resolvers

I have a simple route setup in the following way: RouterModule.forChild([ { path: '', resolve: { data: DataResolver, stuff: StuffResolver, // <-- This requires data from DataResolver ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

Transforming functions into a new typed object with different function signatures

I am currently updating some React/Redux code that previously followed an older pattern to a more modern "hooks" based approach, using TypeScript. In the old pattern, we utilized "class-based" components and passed their "dispatch" functions using mapDisp ...

A TypeScript interface can inherit from either one of two other interfaces

Imagine I have these two different interfaces: interface Bird { type: 'bird'; flyingSpeed: number; } interface Horse { type: 'horse'; runningSpeed: number; } Now, the challenge is to create a new interface that extends ...

Is it possible to replace checkboxes with dropdowns in the NG-ZORRO Tree component?

I am attempting to create a tree structure using the tree component from ng-zorro. However, instead of checkboxes for the leaf nodes, I would like to have dropdown menus. I tried using the ng-template but the checkbox is still appearing. Here is my code: ...