首页 > 解决方案 > 在我的测试 Angular 项目中,我认为我的映射功能有问题

问题描述

它应该调用 pixabay API 来搜索图像。其他一切似乎都很好,但是当我搜索任何东西时,我没有得到图像结果。我认为这是因为映射线但不确定,我是 Angular 的初学者

import {Injectable} from '@angular/core';
import { environment } from '../../environments/environment';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators'

@Injectable()
export class ImageService{
  private query: string;
  private API_KEY: string = environment.PIXABAY_API_KEY;
  private API_URL: string = environment.PIXABAY_API_URL;
  private URL: string = this.API_URL + this.API_KEY + '&q=';
  private perPage: string = "&per_page=10";

constructor(private _http: Http) { }

getImage(query){
    return this._http.get(this.URL + query + this.perPage).map(res => 
        res.json());
    }
}

这是我的 image-list.component.ts 的片段:

handleSuccess(data){
   this.imagesFound = true;
   this.images = data.hits;
   console.log(data.hits);
 }


 handleError(error){
  console.log(error);

 }

constructor(private _imageService : ImageService) { }

searchImages (query: string){
    return this._imageService.getImage(query).subscribe(
        data => this.handleSuccess(data),
        error => this.handleError(error),
        () => this.searching = false
    );
}

ngOnInit() {}

标签: angulartypescriptmapping

解决方案


您看到的错误消息是;

 ERROR TypeError: this._http.get(...).map is not a function at ImageService.push../src/app/shared/image.service.ts.ImageService.getImage (image.service.ts:18) at ImageListComponent.push../src/app/image-list/image-list.component.ts.ImageListComponent.searchImages (image-list.component.ts:30) at Object.eval [as handleEvent] (ImageListComponent.html:7) at handleEvent (core.js:10258)

它提到这map不是一个功能。需要导入;

import 'rxjs/add/operator/map'

您使用的导入不是访问此功能的正确方法。

import { map } from 'rxjs/operators'

有关更多信息,请参阅其他StackOverflow 帖子,其中更详细地解释了该解决方案。


推荐阅读