我必须从flickr API获取数据。恰好我需要URL中的“照片”数组:
当我获取app.component中的数据并对其进行操作时,它可以工作,但是我知道这不是一个好的解决方案。
我尝试过:
photo.ts:
export class Photo {
title: string;
farm: number;
secret: string;
server: string;
owner: string;
id: string;
};
app.component.ts:
export class AppComponent implements OnInit {
photos: Photo[];
constructor(private http: HttpService) {}
ngOnInit() {
this.getData();
}
getData() {
this.http.getData().subscribe(data => {
this.photos = data;
});
}
}
还有我的主要问题http.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Photo } from './photo';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http: HttpClient) { }
getData(): Observable<Photo[]> {
return this.http.get('https://api.flickr.com/path')
.map(res => res.photos.photo);
}
}
在我看来一切正常,但出现错误:
ERROR in src/app/http.service.ts(18,23): error TS2339: Property 'photos' does not exist on type 'Object'.
编辑:
res:
答案 0 :(得分:2)
尝试将res隐式设置为'any'
getData(): Observable<Photo[]> {
return this.http.get('https://api.flickr.com/path')
.map((res:any) => res.photos.photo);
}
答案 1 :(得分:0)
在您的photo.ts中尝试此操作以匹配响应结构
export interface Photo {
title: string,
farm: number,
secret: string,
server: string,
owner: string,
id: string,
isFriend: number,
isFamily: number,
isPublic: number
};
然后在您的回调中将其更改为this.photos = data.photos.photo
答案 2 :(得分:0)
这是一个非常有用的视频,其中有一个很好的示例,可以使用angularjs从api中获取数据