【发布时间】:2016-06-24 03:14:38
【问题描述】:
在 Angular 2 的官方教程中,他们使用 Promise.resolve(HEROES) 来获取 HEROES 数组。
我尝试按照 Http Client 教程进行操作,但遇到了一些问题。我可以发出请求,但是当我导航到其他页面时,它会再次发出 get 请求。不同的组件使用他们自己的 HEROES。
我想知道他们为什么会有不同的行为。如果我想与服务器通信并且仍然使组件使用同一组 HEROES,我该怎么办?
教程现场示例:(https://angular.io/resources/live-examples/toh-5/ts/plnkr.html)
我的试用:(http://plnkr.co/edit/mPgpt2snK2OY6o8sq6YK?p=preview)
我的不同之处在于……
(1) Angular 官方版本的app/hero.service.ts
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Injectable } from 'angular2/core';
@Injectable()
export class HeroService {
getHeroes() {
return Promise.resolve(HEROES);
}
getHero(id: number) {
return Promise.resolve(HEROES).then(
heroes => heroes.filter(hero => hero.id === id)[0]
);
}
}
(2) 我的app/hero.service.ts
版本import {Http, Response} from 'angular2/http';
import {Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Injectable } from 'angular2/core';
@Injectable()
export class HeroService {
constructor (private http: Http) {}
getHeroes() {
return this.http.get("hero.json")
.map(res => <Hero[]> res.json().HEROES)
.do(data => console.log(data)) // eyeball results in the console
.catch(this.handleError);
}
getHero(id: number) {
return this.http.get("hero.json")
.map(res => <Hero> res.json().data.filter(hero => hero.id === id)[0])
.do(data => console.log(data)) // eyeball results in the console
.catch(this.handleError);
}
private handleError (error: any) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Promise.reject(error.message || error.json().error || 'Server error');
}
}
【问题讨论】:
标签: angular