rüf*_*ff0 0 typescript angular2-observables angular angular-httpclient angular7
我正在尝试HttpClient在Angular 7中使用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"
},
...
Run Code Online (Sandbox Code Playgroud)
错误代码是:
error TS2740: Type 'Observable<Object>' is missing the following properties from type 'any[]': length, pop, push, concat, and 25 more.
Run Code Online (Sandbox Code Playgroud)
您需要从方法an返回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));
}
}
Run Code Online (Sandbox Code Playgroud)
从项目的另一个地方
...
imageService.getImages().subscribe(images => /*...*/)
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1720 次 |
| 最近记录: |