json TypeError:无法使用Angular v6读取未定义的属性“map”

sauutmhj  于 2022-12-24  发布在  Angular
关注(0)|答案(5)|浏览(120)

For some reason the response JSON is not mapping correctly Here is my html. profile-search.component.html

<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>`enter code here`
  </li>
</ul>

Here is component that the html pulls from. profile-search.component.ts

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; }

}

Service that component pulls from. profile-search.service.ts

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) {
    // npm package name search api
    // e.g., http://npmsearch.com/query?q=dom'
    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[]> {
    // clear if no pkg name
    if (!packageName.trim()) { return of([]); }

    // const options = createHttpOptions(packageName, refresh);

    // TODO: Add error handling
    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 tried to alter

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 keep getting the below error.
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 (map.js:75) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:81) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93) at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:85) at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93) at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:136) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:20) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93)

yduiuuwa

yduiuuwa1#

data.results中的results可能是undefined,请检查data对象是否与您期望的模式匹配。

xfyts7mz

xfyts7mz2#

map正在array上运行,但此. http.get(${searchUrl}/${packageName})返回对象不是数组。
因此data.results是未定义的。

jhdbpxl9

jhdbpxl93#

这是我如何把我的对象转换成一个数组,如果有人有更好的方法,请让我知道。

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')))
);

}}

hc8w905p

hc8w905p4#

我通过删除“.results”修复了此问题

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

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

643ylb085#

要避免此错误,请更改

map((items) => items.map

map((items) => items?.map

然后将结果集设置为空数组:

this.list = data ?? [];

PS:与Angular 14一起使用。在旧版本中,您可能需要将最后一个更改为data?data:[]

相关问题