Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度-从API获取数据_Angular_Typescript - Fatal编程技术网

Angular 角度-从API获取数据

Angular 角度-从API获取数据,angular,typescript,Angular,Typescript,我必须从flickr API获取数据。确切地说,我需要从我的URL“照片”数组。 当我在app.component中获取数据并对任何组件进行操作时,它都会工作,但我知道这不是一个好的解决方案 我试过: photo.ts: export class Photo { title: string; farm: number; secret: string; server: string; owner: string; id: string; };

我必须从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:

export class HttpService {

  constructor(private http: HttpClient) { }

  getData(): Observable<Photo[]> {
    return this.http.get('https://api.flickr.com/path')
      .map(res => res.photos.photo);
  }
}

请在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

尝试将res隐式设置为“any”

getData(): Observable<Photo[]> {
  return this.http.get('https://api.flickr.com/path')
    .map((res:any) => res.photos.photo);
}
getData():可观察{
返回此.http.get('https://api.flickr.com/path')
.map((res:any)=>res.photos.photo);
}

这是一个非常有用的视频,有一个很好的示例,可以使用angularjs从api获取数据


照片或图片的结果是什么。您检查了吗?
点击
地图之前的
以验证结果。@Manjunath我编辑了问题并添加了console.log(res)img。但是请稍候,这是一个运行时错误还是编译时错误?这是一个编译时错误不幸的是它没有帮助。你也需要在回调中对此进行更改。photos=data.photos.photoHi,AngularJS与Angular(或Angular 2+)不同,它们非常不同。AnajuarJS可以嵌入任何HTML代码、cshtml、php等,但主要用作独立的前端应用程序。
getData(): Observable<Photo[]> {
  return this.http.get('https://api.flickr.com/path')
    .map((res:any) => res.photos.photo);
}