我正在尝试在Angular 7中使用HttpClient
获取JSON。
代码可以正常工作,但是我正在尝试实现注释的代码,并停止使用CONST IMAGES
并直接从api抓取此数据,我还不能这样做。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ImageService {
// public _url: string = "https://jsonplaceholder.typicode.com/photos";
constructor(
// public http: HttpClient
) {}
theImages = [];
// IMAGES = [];
getImages(){
// this.IMAGES = this.http.get(this._url);
return this.theImages = IMAGES.slice(0);
}
getImage(id: number){
// this.IMAGES = this.http.get(this._url);
return IMAGES.slice(0).find(image => image.id == id);
}
}
const IMAGES = [
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
...
错误代码是:
error TS2740: Type 'Observable<Object>' is missing the following properties from type 'any[]': length, pop, push, concat, and 25 more.
答案 0 :(得分:7)
您需要从方法中返回Observable
然后订阅ImageService
实例的方法返回的数据。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { first } from 'rxjs/operators';
@Injectable()
export class ImageService {
public _url: string = "https://jsonplaceholder.typicode.com/photos";
constructor(public http: HttpClient) {}
getImages() {
return this.http.get(this._url);
}
getImage(id: number) {
return this.http.get(this._url)
.pipe(first(item => item.id === id));
}
}
从项目中的另一个地方
...
imageService.getImages().subscribe(images => /*...*/)
...