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

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

问题描述

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

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

想法

我有一个商品页面,我称之为优惠券,点击优惠券中的一个商品,您就会进入一个单优惠券.当我点击 coupons 中的一个项目时,我想将项目数据保存在一个服务中,以便我可以在 single-coupon

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;
})

优惠券中的一些代码Ctrl

.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 & 轻松设置数据值.通过 getCoupon 方法获取数据

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

优惠券Ctrl

.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();
});

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

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