在我的测试Angular项目中,我认为映射功能出了点问题

时间:2018-09-19 15:38:38

标签: angular typescript mapping

应该调用picture来搜索图像。其他一切似乎都很好,但是当我搜索任何东西时,都没有图像的结果。我认为是由于映射线的缘故,但不确定,我是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() {}

1 个答案:

答案 0 :(得分:0)

您看到的错误消息是;

 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 post,其中更详细地介绍了该解决方案。