【问题标题】:Can't handle api response by get method in angular2?无法通过 angular2 中的 get 方法处理 api 响应?
【发布时间】:2016-07-15 10:04:56
【问题描述】:

我一直在尝试使用 angular2 从 api (http://www.cricapi.com/how-to-use.aspx) 获得响应。我不知道我做错了什么?这是我的代码--

//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!

【问题讨论】:

  • 这里没有 Angular 代码,你不能在 Angular 中使用常规的 javascript 类。应用模块、控制器和/或工厂在哪里?
  • @johan 这可能是 TypeScript
  • sry 伙计们!我刚刚发现 angular 和 angular2 完全不同!是的,它的打字稿!
  • 也是我的错,我确定问题被标记为 AngularJS not 2...

标签: json api http angular


【解决方案1】:

我不确定您尝试使用哪种语言编写代码,但使用常规角度时,您只需将 JSON 返回的结果分配给一个变量,它将保存完整的 JSON 对象,如下所示:

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

【讨论】:

  • 它的 angular2!就是这样!
猜你喜欢
  • 2017-09-28
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多