Angular 2:使用服务从其他视图更新列表(http + json)

时间:2016-09-30 20:13:37

标签: angularjs angular service ionic-framework

我在这里发表的第一篇文章:嗨!坚持Ionic 2(2.1.0-beta.1)/ Angular 2问题我希望你们能帮助我:

我的基本设置是:

  • 第1页“收藏”列表
  • 第二页,搜索+可能将其中一个结果添加到第1页列表

要从两个页面访问该对象,我正在使用服务。

第一页html,收藏夹直接引用服务对象。

<ion-list *ngFor="let fav of stationsService.favs">
    {{fav.image}}
</ion-list>

在服务的构造函数中,我得到了当前的收藏夹。

@
Injectable()
export class stationsService {
    public headers: Headers;
    public favs: any;

constructor(private http: Http) {
    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/json');
    this.getFavorites()
        .subscribe(data => {
        this.favs = data;
        });
}
getFavorites() {
    return this.http.get('http://localhost:3000/favorite_stations')
    .map(res => res.json());
}

......哪个有效。当我现在进入搜索页面并将一个项目添加到列表中时,数据会更新(后期工作)但是一旦我回去,列表仍然是相同的。这是我从服务中添加的功能。

    addFavorite(station) {
        return this.http
        .post('http://localhost:3000/favorite_stations', station, {
        headers: this.headers
        })
        .map(res => res.json())
        .subscribe(data => {
        this.favs.push(data);
        });
    }

知道我的错误可能是什么吗?谢谢!

0 个答案:

没有答案