Issue with Undefined Array in Angular 2 App

I've encountered an issue while attempting to save JSON data from my API into an array of Model objects. Despite trying different approaches, the console always logs "undefined" when I try to print the array. This even happens with a simple array that should work fine. I'm quite new to Angular 2 and TypeScript, so any help on what might be missing in my code would be greatly appreciated.

results : Array<Recipes> = new Array(20);
  sample = ['one','two','three'];

  getResults(): Observable<Recipes[]>{

    return this.http.get('<my perfectly functioning API endpoint here>')
      .map(this.extractData)
      .catch(this.handleErrorObservable);
  }

  private extractData(res: Response) {
    let body = res.json();

    console.log(this.sample); **---> Prints undefined in console**

    console.log(body);
    console.log(body.pagination.count);

    let total_no_of_results = body.pagination.count;
    let no_of_results;

    for(no_of_results = 0; no_of_results < total_no_of_results; no_of_results++) {
      //this.results[no_of_results] = new Recipes();
      this.results[no_of_results] = body.data[no_of_results].embed_url; **---> Throws "Cannot set property '0' of undefined" error and stops execution**
    //this.results.push(image);
    }
    console.log(this.results);
    return this.results;
  }

  private handleErrorObservable (error: Response | any) {
    console.error(error.message || error);
    return Observable.throw(error.message || error);
  }

Answer №1

In order to utilize this within the confines of extractData, you must include

.map(this.extractData.bind(this))

alternatively

.map((data) => this.extractData(data))

if not, this will not reference the present class' instance.

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

The pipe in Angular 2.0.0 was not able to be located

Error: Issue: Template parse errors: The 'datefromiso' pipe is not recognized Custom Pipe: import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'datefromiso' }) export class DateFromISO implements P ...

Angular Version 11 is throwing a NullInjectorError with the message: "No provider found for Control

I recently implemented a custom input component based on the guidance provided in this interesting article: medium.com: dont-reinvent-the-wheel. Below is the code snippet I used, written in strict mode ▼ // input.component.ts import { Component, Input, ...

Issue with retrieving the value from a BehaviorSubject in Angular 8 resulting in null output

I am currently setting up an authentication solution by following this tutorial: Within the AuthenticationService, the constructor performs the following operations: constructor(private http: HttpClient) { this.currentUserSubject = new BehaviorSubjec ...

Utilizing Java to showcase individual elements from a List in string format

I'm currently working my way through a tutorial on Streams, but I'm struggling to figure out how to make the List elements display the numbers they contain. If you have two lists of numbers, how would you go about returning all possible pairs? ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

Combine an array in Laravel's Collection class into a cohesive unit

I have an array that is structured like the code below: $arr = ["a", "b", "c", 1, 2, 3, 4, 5, 6]; Utilizing Laravel Collection with this array would result in the following code: $collect = collect($arr); I attempted to use the code snippet below but it ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Upgrading to Angular 6 causes Linter to become significantly more stringent

Recently, I made the jump to Angular 6 and am currently in the process of deploying it. However, I have encountered a major roadblock. The latest issue that I'm facing is an extremely strict linter. When I try to deploy my application using firebase d ...

Insert data into a multi-dimensional array using a consistent key identifier

If I start with the following PHP arrays: <?php $array1= array ( "John" => array("10" , "Holland"), "Cindy" => array("20" , "Sweden"), ); $array2= array ( "John" => ("Amsterdam"), "Cindy" => ("Stockholm"), ); ?> Is ...

Obtain the identifier for the navigation hyperlink

I need to dynamically add an ID using JavaScript @Component({ selector: 'kit-general-16', templateUrl: './16.component.html', styleUrls: ['./16.component.scss'], }) export class CuiGeneral16Component implements OnChanges ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...

What could be causing me to iterate fewer times than I had anticipated?

After I calculated sizeof(array)/sizeof(*array), it returned the value three. However, when passing the array into a function and storing it in a variable, it only prints out 2. This results in the iteration being one less than what is expected. void pri ...

Tips on utilizing *ngFor to showcase a single element within an array

In my component.ts file, I created an array named title: this.projectInfo = { title: [ 'Title 1', 'Title 2', 'Title 3', 'Title 4', 'Title 5', &apos ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Changing a PHP array into Javascript format

Is there a way to transform a PHP array structured like this Array ( [0] => 001-1234567 [1] => 1234567 [2] => 12345678 [3] => 12345678 [4] => 12345678 [5] => AP1W3242 [6] => AP7X1234 [7] => AS1234 ...

Simple method to determine if a variable belongs to an enumeration

Among the numerous discussions on this topic, none seem to focus on developing a versatile function. This function should take an enum and a variable as input, check if the variable is part of that enum, and update the variable type if it is. I have made ...

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

How can I provide a default value, other than zero, for a number type in zod and react-hooks-form?

I am currently using zod and react-hooks-form for my form. One issue I have encountered is with the input field for the price. In order to prevent uncontrolled input errors, defaultValues must be provided. However, this requires me to set the default value ...

Transform a collection of Spark features into a single, compacted array

Building upon my previous inquiry, which can be found here, I have made some advancements: def extractUdf = udf((v: SDV) => v.toArray) val temp: DataFrame = dataWithFeatures.withColumn("extracted_features", extractUdf($"features")) temp.printSchema() ...

Toggle button in Angular 9 to control visibility of a div element

Within my Angular application, I have two distinct components. The first component is a top navigation bar with a toggle button. The second component is a Dashboard located in a separate module. The Dashboard consists of two div elements where one or the ...