typescript - 如何在 Angular 7 中從 API 發送 GET 請求
我正在嘗試使用 Angular 7 中的 HttpClient 來獲取 JSON。代碼運行正常,但我正在嘗試實現註解掉的那幾行,以便直接從 API URL 獲取數據,而不再使用 const IMAGES。
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.
答案#1
你需要從方法中回傳一個 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 => /*...*/)
...
