简体   繁体   English

类型错误:无法使用 Angular v6 读取未定义的属性“映射”

[英]TypeError: Cannot read property 'map' of undefined with Angular v6

For some reason the response JSON is not mapping correctly Here is my html.由于某种原因,响应 JSON 未正确映射这是我的 html。 profile-search.component.html配置文件搜索.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.这是 html 从中提取的组件。 profile-search.component.ts配置文件搜索.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配置文件搜索.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.登录:data.login 和登录:entry.login 但不断出现以下错误。

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 http-error-handler.service.ts:33 类型错误:无法在 MapSubscriber.push 的 MapSubscriber.project (profile-search.service.ts:49) 中读取未定义的属性“地图”../node_modules/rxjs/_esm5/internal /operators/map.js.MapSubscriber._next (map.js:75) 在 MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93) 在 MapSubscriber.push ../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:81) 在 MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next ( Subscriber.js:93) 在 FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:85) 在 FilterSubscriber.push../node_modules/rxjs/_esm5/ internal/Subscriber.js.Subscriber.next (Subscriber.js:93) 在 MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:136) 在 InnerSubscriber。推../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) .InnerSubscriber._next (InnerSubscriber.js:20) 在 InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93)

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

map working on array but this.http.get( ${searchUrl}/${packageName} ) return object not array. map工作在array但this.http.get( ${searchUrl}/${packageName} )返回的对象不是数组。

so data.results is undefined. 所以data.results是未定义的。

This is how I converted my object into an array, if anyone has a better way of doing please let me know. 这就是我将对象转换为数组的方式,如果有人有更好的方法,请告诉我。

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

} } }}

I fixed this issue by eliminating ".results" 我通过消除“.results”解决了这个问题。

from

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

to

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

To avoid the error, change为避免错误,请更改

map((items) => items.map 

to

map((items) => items?.map

Then set your result set as an empty array:然后将结果集设置为空数组:

this.list = data ?? [];

PS: Used with Angular 14. In older versions you may need to change last one to data? PS:与 Angular 14 一起使用。在旧版本中,您可能需要将最后一个更改为数据? data: []数据: []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误TypeError:无法读取undefined |的属性“0” Angular 4 - ERROR TypeError: Cannot read property '0' of undefined | Angular 4 Angular 4 TypeError:无法读取未定义的属性“ IndustrySegments” - Angular 4 TypeError: Cannot read property 'IndustrySegments' of undefined 类型错误:无法读取数组内未定义状态对象的属性“map”? - TypeError: Cannot read property 'map' of undefined state object inside array? TypeError:无法读取未定义的 React Native 的属性“地图” - TypeError: Cannot read property 'map' of undefined React Native 我不断收到此类型错误:无法读取未定义的属性“地图” - I keep getting this TypeError: Cannot read property 'map' of undefined 类型错误:无法读取反应组件中未定义的属性“映射” - TypeError: Cannot read property 'map' of undefined in react component 服务器错误类型错误:无法读取未定义的属性“地图” - Server Error TypeError: Cannot read property 'map' of undefined TypeError:无法读取未定义的属性“地图”。 反应 - TypeError: Cannot read property 'map' of undefined. React Angular JS TypeError:无法读取Route上未定义的属性“id” - Angular JS TypeError: Cannot read property 'id' of undefined on Route 角数组:错误类型错误:无法读取未定义的属性 - Angular array: ERROR TypeError: Cannot read property of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM