我必须从 flickr API 获取数据。准确地说,我需要 URL 中的“照片”数组。 当我获取 app.component 中的数据并对其进行操作时,它可以工作,但我知道这不是一个好的解决方案。
我尝试过:
照片.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:
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 隐式设置为“any”
getData(): Observable<Photo[]> {
return this.http.get('https://api.flickr.com/path')
.map((res:any) => res.photos.photo);
}
关于Angular - 从 API 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53383288/