Angular-从API获取数据

时间:2018-11-19 22:03:59

标签: angular typescript

我必须从flickr API获取数据。恰好我需要URL中的“照片”数组:

enter image description here

当我获取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:

enter image description here

3 个答案:

答案 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中获取数据

https://www.youtube.com/watch?v=Lp8d4VZyhZc&t=666s