The error caused by Angular v6 is: "TypeError: Unable to access the 'map' property because

It seems that the response JSON is not mapping correctly as expected. Below is the HTML code:

<h3>Enter Username</h3>
<input (keyup)="search($event.target.value)" id="name" placeholder="Search"/>
<ul>
  <li *ngFor="let package of packages$ | async">
    <b>{{package.name}} v.{{package.repos}}</b> -
    <i>{{package.stars}}</i>
  </li>
</ul>

This is the component that the HTML pulls from:

import { Component, OnInit } from '@angular/core';

import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

import { NpmPackageInfo, PackageSearchService } from './profile-search.service';

@Component({
  selector: 'app-package-search',
  templateUrl: './profile-search.component.html',
  providers: [ PackageSearchService ]
})
export class PackageSearchComponent implements OnInit {
  withRefresh = false;
  packages$: Observable<NpmPackageInfo[]>;
  private searchText$ = new Subject<string>();

  search(packageName: string) {
    this.searchText$.next(packageName);
  }

  ngOnInit() {
    this.packages$ = this.searchText$.pipe(
      debounceTime(500),
      distinctUntilChanged(),
      switchMap(packageName =>
        this.searchService.search(packageName, this.withRefresh))
    );
  }

  constructor(private searchService: PackageSearchService) { }


  toggleRefresh() { this.withRefresh = ! this.withRefresh; }

}

The service that the component pulls data from:

import { Injectable, Input } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

import { HttpErrorHandler, HandleError } from '../http-error-handler.service';

export interface NpmPackageInfo {
  name: string;
}

export const searchUrl = 'https://api.github.com/users';

const httpOptions = {
  headers: new HttpHeaders({
    'x-refresh':  'true'
  })
};

function createHttpOptions(packageName: string, refresh = false) {
    const params = new HttpParams({ fromObject: { q: packageName } });
    const headerMap = refresh ? {'x-refresh': 'true'} : {};
    const headers = new HttpHeaders(headerMap) ;
    return { headers, params };
}

@Injectable()
export class PackageSearchService {
  private handleError: HandleError;

  constructor(
    private http: HttpClient,
    httpErrorHandler: HttpErrorHandler) {
    this.handleError = httpErrorHandler.createHandleError('HeroesService');
  }

  search (packageName: string, refresh = false): Observable<NpmPackageInfo[]> {
    if (!packageName.trim()) { return of([]); }

    return this.http.get(`${searchUrl}/${packageName}`).pipe(
      map((data: any) => {
        return data.results.map(entry => ({
            name: entry.any[0],
          } as NpmPackageInfo )
        )
      }),
      catchError(this.handleError('search', []))
    );
  }
}

I have attempted to change the following lines in the code:

return this.http.get(`${searchUrl}/${packageName}`).pipe(
    map((data: any) => {
        return data.results.map(entry => ({
            name: entry.any[0],
          } as NpmPackageInfo )
        )

to login: data.login and login: entry.login but encountering the error mentioned below:

http-error-handler.service.ts:33 TypeError: Cannot read property 'map' of undefined at MapSubscriber.project (profile-search.service.ts:49) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next ...

Answer №1

outcome in data.outcome may be unavailable, review if the data structure aligns with the anticipated schema.

Answer №2

map functions correctly when applied to an array, however, the result of this.http.get(${searchUrl}/${packageName}) is not an array but an object.

Due to this, accessing data.results results in it being undefined.

Answer №3

Here is my approach to converting an object into an array. If you have a more efficient method, I would appreciate your input.

return this.http.get(`${searchUrl}/${packageName}`).pipe(
  map((data: any) => {
    console.log(data);
    var profile = Object.keys(data).map(function(key) {
      return [(key) + ': ' + data[key]];
    } 
  );
    console.log(profile);
    data = profile;
    return data;
  }),
  catchError(this.handleError<Error>('search', new Error('OOPS')))
);

}

Answer №4

To resolve the problem, I removed ".results"

within

.map((data: any) => this.convertData(data.results))

and changed it to

.map((data: any) => this.convertData(data))

Answer №5

To prevent the error, simply modify

map((items) => items.map 

to

map((items) => items?.map

After that, initialize your result set as an empty array:

this.list = data ?? [];

Note: This was tested with Angular 14. For older versions, you might have to adjust the last line to data ? data : []

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

Tips for formatting numbers within a chart

One issue in my chart is that the values are not formatted correctly. For instance, I have a number 15900 and I would like it to be displayed as 15 900 with a space between thousands and hundreds. Below is the code snippet I would like to implement for s ...

Ways to invoke a function in an angular component from a separate component located in a different .ts file

File3.ts export class3(){ method1(x,y){ .... } } File4.ts export class4(){ a: string = "abc" b: string ="xyz" //How can I call method1 and pass parameters from file 3? method1(x,y); } I attempted the following in Fi ...

Populate Android RecyclerView with Images and Text from JSON Data

Hello, I am currently working on creating a RecyclerView list from JSON data that includes image URLs and names. I have spent the past two days searching Google and Stack Overflow for a solution, but I have not been able to figure out how to set the text a ...

The MatFormField component requires a MatFormFieldControl to be present in order to function properly. This error may occur if the

HTML CODE `<mat-form-field> <input type="file" (change)="onFileSelected($event)" name="categoryImage" > </mat-form-field>` TS code onFileSelected(event){ console.log(event);} Encountering an error even before beginning the ope ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

Issue with the dropdown functionality in an Angular reactive form

I am experiencing an issue with a select dropdown in my Angular project. I have implemented a reactive form, but the dropdown is not functioning as expected and I am unsure of how to resolve this issue. Could someone offer assistance or guidance on how to ...

How can Python implement JSON templates?

Is it possible to create a template in json/yaml and populate values based on context? root: child: {{child_value}} other_child: 1 For example, could I use the following code: output = format("template.yaml", context=dict(child_value=1)) T ...

What is the best way to connect an event in Angular 2?

This is an input label. <input type="text" (blur) = "obj.action"/> The obj is an object from the corresponding component, obj.action = preCheck($event). A function in the same component, preCheck(input: any) { code ....}, is being used. Will it wor ...

Can auto-import be configured in WebStorm without using double dots?

Is it feasible to configure WebStorm for automatic import of modules/Component/components/MyComponent instead of using ../MyComponent? ...

Using v-show in a Vue component of my own creation throws an TypeError: Unable to access property '_withTask' of undefined

I created a custom Vue component called "editable-image" as shown below: <template> <span style="position: relative; text-align: center; color: white; cursor: pointer; margin-right: 10px;" @mouseover="iconShown = true" @mouseleave="iconShown = ...

Is the JSON data not formatted correctly when utilizing the Pivotal API?

Attempting to integrate the Pivotal API with PHP has led me to encounter a JSON-related issue. The current version 5 utilizes JSON instead of XML, unlike previous versions. My attempt at coding this integration is as follows: public function updateStory($ ...

Connecting data with Ember CLI and ASP.NET WebAPI

I am facing an issue with integrating my Ember Cli project running on localhost:4200 and my asp.net webapi project running on localhost:56967. Both projects function properly individually: I can run my Ember app, test various routes, and access my api succ ...

In the realm of Swift programming, lies the intriguing task of parsing a JSON file that is securely stored on a

I am new to the concept of JSON parsing. Currently, I am attempting to retrieve data from a local JSON file in my Swift project. I have successfully implemented the code to fetch the data. However, I am facing difficulties in creating an array of objects b ...

Error Encountered with CakePHP Model when Parsing AJAX JSON Data

I encountered a problem with AJAX while developing an application using CakePHP 2.5.3.0 My AJAX request from jQuery to CakePHP is meant to send the user's login and password, expecting a validated JSON response. However, when using a Model method wit ...

iPhone - Yet another memory leak discovered in Objective-C due to SBJsonParser

Hi there! I'm fairly new to iPhone development and exploring Stack Overflow for answers. It's been a journey working on my first app since January. Currently, I've encountered a memory leak issue associated with SBJsonParser in my app. Afte ...

The default value for the logged in user in Angular 7 is set to null when

In my login component, I have a form where users can enter their credentials and submit for authentication using the following function: this.auth.login(this.f.email.value, this.f.password.value) .pipe(first()) .subscribe( data ...

I am receiving data from a web service on my Android device

START D/OkHttp: Specific Gravity Before Charging : 150,150,150,150,150,150 D/OkHttp: Specific Gravity After Charging : 150,150,150,150,150,150 D/OkHttp: Battery Serial : 2bea79b1001000 D/OkHttp: Battery AH : 150 D/OkHttp: Battery Type : INVERTER ...

Sending information from service.ts to component

I'm encountering a roadblock with this issue, hopefully I can find some assistance here. Essentially, I am attempting to make a simple get http request in http.service and then pass the json object to the filter.service. From there, I aim to transfer ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

How to create a custom Error page in Next.js using TypeScript

How do I create an Error page in Next.js using Typescript? I attempted the following: interface ErrorProps { statusCode: number; } function Error({ statusCode }: ErrorProps) { return ( <p> {statusCode ? `An error ${statusCode} ...