离子使用服务在控制器之间共享数据 [英] ionic use Service to share data between controllers

查看:140
本文介绍了离子使用服务在控制器之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在控制器之间共享数据但是一旦在我的服务中设置了数据,它就不会再次改变。

I'm trying to share data between controllers but once the data is set in my service it won't change again.

想法

我有一个项目页面我正在调用优惠券并点击优惠券中的项目需要你去单一优惠券。当我点击优惠券中的项目时,我想将商品数据保存在服务中,以便我可以在单优惠券中访问

I have a page of items I'm calling coupons and clicking on an item in coupons takes you to a single-coupon. When I click an item in coupons I want to save the item data in a service so that I can have access to it in single-coupon

服务

.service('userService', function() {
  var userService = this;

  userService.sharedObject = null;
})

CouponsCtrl中的一些代码

.controller('CouponsCtrl', function($scope, $state, userService) {
  $scope.couponClick = function(coupon) {
    userService.sharedObject = coupon;
    $state.go('single-coupon');
  }
})

问题

这是第一次像你期望的那样工作,但如果我回到优惠券并点击一个新的优惠券项目,那么单一优惠券页面仍显示旧数据!我需要做什么不同的事情?

This works the first time like you would expect but then if I go back to coupons and click a new coupon item then the single-coupon page still shows the old data! What do I need to do differently?

推荐答案

基本上你的服务应该有getter和setter来设置&获取数据

Basically your service should have getter and setter which would set & get data

服务

.service('userService', function() {
  var userService = this;
  userService.sharedObject = {};

  userService.getCoupon = function(){
     return userService.sharedObject.Coupon;
  }

  userService.setCoupon = function(value){
     userService.sharedObject.Coupon = value;
  }
});

然后你可以使用set setCoupon 轻松设置数据值code>& getData by getCoupon method

Then you could easily set a value of data by using set setCoupon & getData by getCoupon method

CouponsCtrl

.controller('CouponsCtrl', function($scope, $state, userService) {
  $scope.couponClick = function(coupon) {
    userService.setCoupon(coupon);
    $state.go('single-coupon');
  }
});

SingleCouponCtrl (singleCouponCtrl将获得价值)

SingleCouponCtrl(singleCouponCtrl will get value by)

.controller('singleCouponCtrl', function($scope, $state, userService) {
   //other code here
   if($state.params.id == 0) //id is of coupon id
     $scope.coupon = userService.setCoupon({}); //for your issue
   $scope.coupon = userService.getCoupon();
});

这篇关于离子使用服务在控制器之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆