service - AngularJS: Passing variables between controllers -
i new angular , i'm trying find method of passing variables between controllers. saw best method of achieving using service, shown here - angularjs: how can pass variables between controllers?
however, doesn't seem working code, explain @ bottom.
here service code,
app.service('loginservice', function ($http) { var loggedinuser = [] //if login successful used this.setlogindetails = function(userdetails){ loggedinuser.push(userdetails); } this.getloginusername = function () { return loggedinuser.username; } }); and 2 controllers,
app.controller('logincontroller', function ($scope, $rootscope, loginservice, $location, $window) { $scope.authenticatelogin = function () { // record var user = { username: $scope.username, password: $scope.password }; var promisepost = loginservice.post(user); promisepost.then(function (result) { var res = result.data; //this important line loginservice.setlogindetails(user); $window.location.href = loginpageurl; }, function (errorresult) { console.log("unable log in : " + errorresult); }); } }); my controller trying retrieve information has been set,
app.controller('usercontroller', function ($scope, userservice, $window, $modal, loginservice) { // current logged in user $scope.loggedinas = loginservice.getloginusername(); }); the issue having username being correctly set first controller, when try access information second controller value loggedinuser in null value not being saved between controllers. doing wrong?
var loggedinuser = [] array, if want username have loggedinuser[0].username , not loggedinuser.username.
this.getloginusername = function () { return loggedinuser[0].username; } also, stated in comments either use ngroute/uirouter change page/url...
Comments
Post a Comment