我试图使用服务将数据从一个控制器传递到另一个控制器,但是无论我尝试什么,它总是在第二个控制器上返回“未定义的”。这是我的服务:
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);以下是controller1:
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);然后是controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);这是简单的代码,不幸的是,我已经挣扎了几个小时了,有什么建议吗?谢谢。
发布于 2016-01-21 19:19:28
在这里创建了一个小提琴:http://jsfiddle.net/frishi/8yn3nhfw/16
要隔离这个问题,您能从myService的定义中删除依赖项并查看它是否有效吗?装上小提琴后看控制台。
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})发布于 2016-01-21 18:20:53
我想问题是您要在服务中返回this.savedData。尝试返回savedData。
this在Javascript中的行为与其他语言不同。
https://stackoverflow.com/questions/34931139
复制相似问题