加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS服务在控制器之间传递数据

发布时间:2020-12-17 08:17:16 所属栏目:安全 来源:网络整理
导读:当使用AngularJS服务在两个控制器之间尝试传递数据时,我的第二个控制器在尝试从服务访问数据时始终接收未定义的数据。我猜这是因为第一个服务做了一个$ window.location.href,我在想这是清除服务中的数据?有一种方法可以将URL更改为新位置,并将数据保留
当使用AngularJS服务在两个控制器之间尝试传递数据时,我的第二个控制器在尝试从服务访问数据时始终接收未定义的数据。我猜这是因为第一个服务做了一个$ window.location.href,我在想这是清除服务中的数据?有一种方法可以将URL更改为新位置,并将数据保留在第二个控制器的服务中?当我在下面运行代码时,第二个控制器中的警报总是未定义的。

app.js(定义服务的地方)

var app = angular.module('SetTrackerApp',['$strap.directives','ngCookies']);

app.config(function ($routeProvider) 
{
$routeProvider
  .when('/app',{templateUrl: 'partials/addset.html',controller:'SetController'})
  .when('/profile',{templateUrl: 'partials/profile.html',controller:'ProfileController'})
  .otherwise({templateUrl: '/partials/addset.html',controller:'SetController'});
});

app.factory('userService',function() {
var userData = [
    {yearSetCount: 0}
];

return {
    user:function() {
        return userData;
    },setEmail: function(email) {
        userData.email = email;
    },getEmail: function() {
        return userData.email;
    },setSetCount: function(setCount) {
        userData.yearSetCount = setCount;
    },getSetCount: function() {
        return userData.yearSetCount;
    }
};
});

logincontroller.js :(控制器1设置服务中的值)

app.controller('LoginController',function ($scope,$http,$window,userService) {

$scope.login = function() {
    $http({
        method : 'POST',url : '/login',data : $scope.user
    }).success(function (data) {
        userService.setEmail("foobar");
        $window.location.href = '/app'
    }).error(function(data) {
        $scope.login.error = true;
        $scope.error = data;
    });
}
});

appcontroller.js(第二个控制器试图从服务中读取价值)

app.controller('AppController',function($scope,userService) {

$scope.init = function() {      
    alert("In init userId: " userService.getEmail());
}

});
定义你这样的服务
app.service('userService',function() {
  this.userData = {yearSetCount: 0};

  this.user = function() {
        return this.userData;
  };

  this.setEmail = function(email) {
        this.userData.email = email;
  };

  this.getEmail = function() {
        return this.userData.email;
  };

  this.setSetCount = function(setCount) {
        this.userData.yearSetCount = setCount;
  };

  this.getSetCount = function() {
        return this.userData.yearSetCount;
  };
});

在这里查看邓肯的回答:

AngularJS – what are the major differences in the different ways to declare a service in angular?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读