首页 文章

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

提问于
浏览
0

由于某种原因,响应JSON未正确映射这是我的html . 型材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>

这是html提取的组件 . 型材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; }

}

组件来自的服务 . 型材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', []))
    );
  }
}

我试图改变

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

登录:data.login和login:entry.login但不断收到以下错误 .

http-error-handler.service.ts:33 TypeError:在MapSubscriber.push ../ node_modules / rxjs / _esm5 /中无法读取MapSubscriber.project(profile-search.service.ts:49)中未定义的属性'map'在MapSubscriber的MapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next(Subscriber.js:93)中的internal / operators / map.js.MapSubscriber._next(map.js:75) . 在MapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next中推送../ node_modules / rxjs / _esm5 / internal / operators / map.js.MapSubscriber._next(map.js:81) (Subscriber.js:93)位于FilterSubscriber.push ../ node_modules / rxjs / _esm5的FilterSubscriber.push ../ node_modules / rxjs / _esm5 / internal / operators / filter.js.FilterSubscriber._next(filter.js:85) /internal/Subscriber.js.Subscriber.next(Subscriber.js:93)位于InnerSubscriber的MergeMapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / operators / mergeMap.js.MergeMapSubscriber.notifyNext(mergeMap.js:136) .push ../ node_modules / rxjs / _esm5 /内部/ InnerSubscriber . 在InnerSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next(Subscriber.js:93)中的js.InnerSubscriber._next(InnerSubscriber.js:20)

4 回答

  • 0

    我通过消除“.results”解决了这个问题 .

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

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

    results 中的 results 可能是 undefined ,检查 data 对象是否与您期望的架构匹配 .

  • 0

    map 工作在 array 但是this.http.get( ${searchUrl}/${packageName} )返回对象而不是数组 .

    所以 data.results 未定义 .

  • 3

    这就是我将对象转换为数组的方式,如果有人有更好的方法,请告诉我 .

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

    }}

相关问题