2016-07-15 114 views
0

我一直在試圖從api(http://www.cricapi.com/how-to-use.aspx)和angular2中獲得響應。我不知道我做錯了什麼?這裏是我的代碼 -無法通過angular2中的get方法處理api響應?

//matchlist.component.ts 
@Component({ 
selector: 'match-list', 
template: ` 
    <ul> 
    <li *ngFor="let m of matches"> 
    <p>{{m.title}}</p> 
    </li> 
    </ul> 

`, 
providers: [MatchListService] 
}) 

export class MatchList implements OnInit{ 

matches: Match[] = []; 
object: any; 
constructor(private matchservice: MatchListService){ 
} 

ngOnInit(){ 

    this.matchservice.getMatchList() 
     .subscribe(
      matches => this.matches = matches, 
      err => {} 
     ); 

} 
} 

這裏是我的服務接收機類

@Injectable() 
export class MatchListService{ 

private matchListUrl = 'http://cricapi.com/api/cricket/'; 

constructor (private http: Http) { 

} 

getMatchList(): Observable<Match[]>{ 
    return this.http.get(this.matchListUrl, [{}]) 
        .map((res:any) => res.json() 
         .catch(this.handleError)); 
      } 

請告訴我,如果我做了錯誤的方式?這是我第一次使用api!

+0

有這裏沒有角碼,你不能在角度上使用常規的JavaScript類。應用程序模塊,控制器和/或工廠在哪裏? – johan

+0

@johan可能這是TypeScript – Mikhail

+0

sry guys!我剛剛發現角度和角度2是完全不同的!是的,它的打字稿! –

回答

1

我不知道你想代碼,但什麼語言規則的角度你只需指定JSON返回結果給一個變量,它會保持完整的JSON對象,像這樣:

$scope.data = []; 
$http({url: url}).then(function (rs) { 
    console.log(rs); 
    $scope.data = rs.data; 
}); 
+0

其angular2!多數民衆贊成在! –