I'm trying to get the JSON using HttpClient
in Angular 7. The code works fine but I'm trying to implement the commented lines to get the data directly from the API url and stop using the 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 code is:
error TS2740: Type 'Observable<Object>' is missing the following properties from type 'any[]': length, pop, push, concat, and 25 more.
You need to return from the methods an Observable
and then subscribe to the ImageService
instance's methods returned data.
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));
}
}
From another place in your project
...
imageService.getImages().subscribe(images => /*...*/)
...