Angular 4从github api获取数据

时间:2018-03-15 10:35:04

标签: json angular typescript github-api

我尝试从github获取我的最后一次提交。我用过这个github api。 但我得到错误:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

我可以从简单的json获取数据,我使用下面的服务和代码,但现在这对我不起作用。 链接到json: JSON 如果我从这个JSON获取数据,那么我就不会收到错误,而是显示我想要的内容。

我的githubservice:

import { Injectable } from '@angular/core';
import { Http, Response, HttpModule } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IpostsGithub } from './ipostsGithub'
@Injectable()
export class GithubService {

  private _postsURL = "https://api.github.com/repos/objectprogr/Dashboard/git/refs/heads/v1";


  constructor(private http: Http) {

  }

  getPosts(): Observable<IpostsGithub[]> {
      return this.http
          .get(this._postsURL)
          .map((response: Response) => {
              return <IpostsGithub[]>response.json();

          })     
  }

  private handleError(error: Response) {
      return Observable.throw(error.statusText);
  }

}

github组件:

import { Component, OnInit } from '@angular/core';
import { GithubService } from './github.service';
import { IpostsGithub } from './ipostsGithub';

@Component({
  selector: 'app-github',
  templateUrl: './github.component.html',
  styleUrls: ['./github.component.css'],
  providers: [ GithubService]
})
export class GithubComponent implements OnInit {

  _postsArray: IpostsGithub[];
  user: string;
  constructor(private githubService: GithubService, ) {
  }
  getPost(): void {
    this.githubService.getPosts()
        .subscribe(
            resultArray => this._postsArray= resultArray,
            error => console.log("Error :: " + error)
        )
}


ngOnInit(): void {
    this.getPost();
}
}

和html:

<table class="table">
  <thead>
    <th>1</th>
  </thead>
  <tbody>
    <tr *ngFor="let post of _postsArray">
      <td>{{post.message}}</td>
    </tr>
  </tbody>
</table>

这是我收到的错误代码,我在浏览器控制台中找到了它:

_postsArray: […]
0: {…}
object: {…}
sha: "f0814bea75841ef7488552d29c6e1b8ad849f558"
type: "commit"
url: "https://api.github.com/repos/objectprogr/Dashboard/git/commits/f0814bea75841ef7488552d29c6e1b8ad849f558"
__proto__: Object { … }
ref: "refs/heads/v1"
url: "https://api.github.com/repos/objectprogr/Dashboard/git/refs/heads/v1" 

我不知道如何解决它?

2 个答案:

答案 0 :(得分:0)

听起来像API返回一个对象的对象,ngFor只适用于像数组这样的迭代。

答案 1 :(得分:0)

好像你正在获取一个Object而不是一个数组,你想要循环它吗?如果我错了,请纠正我。

如果是这样的话,你就会这样做:

在您的<div *ngFor="let s of streamList;trackBy: streamListTrackFn"> <div class="thumbnail"> <img [attr.src]="data:image/png;base64,{{s.thumbnail}}" /> </div> </div> 文件中

.ts

export class SomeClass { Object: Object; constructor() { ... } }

.html