使用Angular2 Promise从JSON获取数据
发布时间:2020-12-17 07:15:02 所属栏目:安全 来源:网络整理
导读:我正在尝试从Angular2文档中的 http tutorial之后的JSON文件中获取数据: 服务: import { Injectable } from '@angular/core';import { Headers,Http } from '@angular/http';import 'rxjs/add/operator/toPromise';import { Hero } from './hero';private
我正在尝试从Angular2文档中的
http tutorial之后的JSON文件中获取数据:
服务: import { Injectable } from '@angular/core'; import { Headers,Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Hero } from './hero'; private heroesUrl = 'app/heroes'; // URL to web api constructor(private http: Http) { } getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise() .then(response => response.json().data as Hero[]) .catch(this.handleError); } 零件: import { Component,OnInit } from '@angular/core'; import { Hero } from './hero'; import { HeroService } from './hero.service'; @Component({ selector: 'my-app',template: // some template,styles: // some style,providers: [HeroService] }) export class AppComponent implements OnInit { title = 'Tour of Heroes'; heroes: Hero[]; constructor(private heroService: HeroService) { } getHeroes(): void { this.heroService.getHeroes().then(heroes => { this.heroes = heroes; console.log('heroes',this.heroes); }); } ngOnInit(): void { this.getHeroes(); } } 模型: export class Hero { constructor( public id: number,public name: string,public power: string,public alterEgo?: string ) { } } 我取代了私人英雄Url =’app / heroes’;我的端点是一个JSON文件(private heroesUrl =’app / mockups / heroes.json’;),它包含根据英雄模型的数据. 但是当我运行我的应用程序时,我没有数据,并且有任何错误消息. 解决方法
解决方案是JSON对象必须以具有相同名称response.json().data的属性开头.
将第一个属性重命名为数据可以完成工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容