刷新组件可观察到来自Ionic2 / Angular2刷新中另一个组件的新API URL

时间:2016-03-12 05:51:17

标签: modal-dialog angular ionic2 angular2-services

我正在努力解决可能是直截了当的Ionic2 / Angular2问题,但我无法看到解决方案。

我有一个名为Recipes的组件,它在名为DataService的服务中使用来自API调用的数据。这一切都很好。

然后我有另一个组件显示在从Recipes启动的模式中。此组件具有修改API查询的控件(即,调用的URL)。当用户关闭模态时,我想通过使用新URL调用API来刷新Recipes中的数据,但无法弄清楚如何使其工作。

下面是我的recipes.ts,其中包含Recipes的类以及包含DataService代码的modal和my data.ts。

Recipes.ts:

import {Page, Modal, ViewController, NavController, NavParams} from 'ionic-angular';
import {Inject, Injectable} from 'angular2/core';
import {DataService} from '../../service/data.ts';
import {Http, Headers, Request, RequestOptions, RequestMethod} from 'angular2/http';
import 'rxjs/add/operator/map';

@Page({
  templateUrl: 'build/pages/recipes/recipes.html'
})
export class RecipesPage {
  constructor(nav: NavController, dataService: DataService) {
    this.nav = nav;
    this.dataService = dataService;
    this.results = [];
    this.connectData();
  }

  // open filters modal
  openFilters(filters) {
      let modal = Modal.create(filterModal, this.filters);
      this.nav.present(modal);
  }

  connectData() {
    this.dataService.getData('initialQuery')
    .subscribe(data => {
      this.results = data;
      console.log(this.results);
    })
  }

}

// modal logic
@Page({
  templateUrl: 'build/pages/recipes/recipes-modal.html'
})
export class RecipesModal {
  constructor(nav: NavController, params: NavParams, viewCtrl: ViewController, dataService: DataService) {
    this.nav = nav;
    this.dataService = dataService;
    this.params = params;
    this.viewCtrl = viewCtrl;
  }

  close() {
    this.dataService.getData('nextQuery');
    this.viewCtrl.dismiss();
    // how do I update the data displayed by Recipes when this modal is closed?
  }
}

data.ts:

import {Inject, Injectable} from 'angular2/core';
import {Http, Headers, Request, RequestOptions, RequestMethod} from 'angular2/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataService {
  constructor(http: Http) {
    this.http = http;
  }

  // function to
  getData(keyword) {
    let options = new RequestOptions({
      method: RequestMethod.Get,
      url: 'https://api/' + keyword,
    });
    let request = new Request(options);
    return this.http.request(request)
    .map(res => res.json());
  }

}

请让我知道我在这里错过了什么......

1 个答案:

答案 0 :(得分:0)

实际上,在调用dismiss方法时,您可以提供数据。我会以这种方式编写代码:

  close() {
    this.dataService.getData('nextQuery').subscribe(data => {
      this.viewCtrl.dismiss(data);
    });
  }

您可以通过这种方式在其他组件中接收数据:

  openFilters(filters) {
      let modal = Modal.create(filterModal, this.filters);
      modal.onDismiss(data => {
        this.result = data;
      });
      this.nav.present(modal);
  }

请参阅此文档: