将数据从服务发送到工厂

时间:2016-10-19 11:20:30

标签: angularjs ionic-framework

嘿伙计们我正在尝试从auth.service.js中的服务向app.js中的工厂发送变量。我很有新意,所以我很感激任何帮助。



(function() {

  'use strict';

  angular
    .module('app')
    .service('authService', authService);

  authService.$inject = ['$rootScope', 'lock', 'authManager', 'jwtHelper'];

  function authService($rootScope, lock, authManager, jwtHelper) {

    var userProfile = JSON.parse(localStorage.getItem('profile')) || {};

    function login() {
      lock.show();
    }

    // Logging out just requires removing the user's
    // id_token and profile
    function logout() {
      localStorage.removeItem('id_token');
      localStorage.removeItem('profile');
      authManager.unauthenticate();
      userProfile = {};
    }

    // Set up the logic for when a user authenticates
    // This method is called from app.run.js
    function registerAuthenticationListener() {

      lock.on('authenticated', function(authResult) {
        localStorage.setItem('id_token', authResult.idToken);
        authManager.authenticate();
        var pubkey = KEYUTIL.getKey('-----BEGIN CERTIFICATE-----MIIC8DCCAdigAwIBAgIJVUYCZUQdreDfMA0GCSqGSIb3DQEBBQUAMB8xHTAbBgNVBAMTFHN3aXRjaC1hcHAuYXV0aDAuY29tMB4XDTE2MTAwNTE5MzczM1oXDTMwMDYxNDE5MzczM1owHzEdMBsGA1UEAxMUc3dpdGNoLWFwcC5hdXRoMC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTG7oTPof81dqHqDKT8Mi/umpKgALMHJRwXSVIPBtPZGrgyOubi1oPsWZQrYOwla/3fMhstV/g6ZclVLGg9YHwNZl7uZYaOhAX1CjaTnDUe85R0lvFMRO42N5ZdbhXQASPPrMNZL7gov3eBQcj2n+Jb2k7OWYpN2mevw1fd6iah0eKAeoUcoWGjYwkB9DLmN7HizRsMHeVRyx3BJisI1PmFMkR+Ewbdu+HtOf7yavaVS6KmJti/U/192mXDgakRBLeODrZ+AxwedYcaF4CtGyS52SKkkHsbi6KsjDjfc9CbRRM+51VffVNzTsMTHYtADG34KHigGry/x/5QfsCAEXnAgMBAAGjLzAtMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFOUsGT48yyeHc6a/RdMAlasaM3p7MA0GCSqGSIb3DQEBBQUAA4IBAQAeqkTdeYqE1gSauYr/h30OSjxvHgskUOueWvFBnFveiEQWV3eVyu/psn2YG/2QgCeNSWUMsd8SXCAOBilFy6GL27bUmGKoZEDYsm0dUFTxZiTHgJZNMMQIpPtCLw48Ly1BVQQvi21DZnS9G5ZdWbTEwjNK4M+Fil5zgaiJaObRH4+oAXpgwngT+ZoEO3Z38urbs/Gcp1VKvHjEdY18JxyDChQfIDQNb6bc2zoOR62JTx75fC7khQesJ2jcxJhE1VLsvMRr1bVaVgBeEAdq+fC6WQsJA08209JmJfO4/OYscSe9RxnDEXa6UOQpNO34x5Tr8AImQTLy3jdFoNg1/fSL-----END CERTIFICATE-----');
        var isValid = KJUR.jws.JWS.verifyJWT(authResult.idToken, pubkey, {alg: ['RS256']});
        console.log(isValid);
        // Used for decoding the message returned form auth0
        var decoded = jwt_decode(authResult.idToken);
        // The encoded message returned from auth0
        console.log(authResult.idToken);
        //The decoded message returned from auth0
        console.log(decoded);
        lock.hide();

        // Redirect to default page
        location.hash = '#/app/home';

        lock.getProfile(authResult.idToken, function(error, profile) {
          if (error) {
            console.log(error);
          }
          localStorage.setItem('profile', JSON.stringify(profile));
        });
      });
    }

    function checkAuthOnRefresh() {
      var token = localStorage.getItem('id_token');
      if (token) {
        if (!jwtHelper.isTokenExpired(token)) {
          if (!$rootScope.isAuthenticated) {
            authManager.authenticate();
          }
        }
      }
    }

    return {
      userProfile: userProfile,
      login: login,
      logout: logout,
      registerAuthenticationListener: registerAuthenticationListener,
      checkAuthOnRefresh: checkAuthOnRefresh
    }
  }
})();




我想从函数registeredAuthentificationListener()中将authResult.idToken发送到

中的工厂

app.js



(function () {
  var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

  if (iOS) {
      var isApple = 'isApple';
  }else{
      var isApple = 'notApple';
  }
  'use strict';

  var app = angular
    .module('app', ['ionic', 'auth0.lock', 'angular-jwt'])
    .config(config);
  config.$inject = ['$stateProvider', '$urlRouterProvider', 'lockProvider', 'jwtOptionsProvider','$httpProvider'];
  function factory() {
    return {
      request : function (config) {
        config.headers['X-switch-using'] = isApple;
        return config;
      }
    }
  }

  function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider,$httpProvider) {
    $stateProvider

    // setup an abstract state for the tabs directive
    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'components/menu/menu.html',
  })
  .state('app.home', {
      url: '/home',
      views: {
        'menuContent': {
          templateUrl: 'components/home/home.html'
        }
      }
    })
  .state('app.dashboard', {
      url: '/dashboard',
      views: {
        'menuContent': {
          templateUrl: 'components/template/template.html'
        }
      }
    })
    .state('app.signin', {
        url: '/login',
        views: {
          'menuContent': {
            templateUrl: 'components/login/login.html'
          }
        }
      });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/home');
    $httpProvider.interceptors.push(factory);

    lockProvider.init({
      clientID: AUTH0_CLIENT_ID,
      domain: AUTH0_DOMAIN,
      options: {
        auth: {
          redirect: false,
          params: {
            scope: 'openid',
            device: 'Mobile device'
          }
        }
      }
    });

    // Configuration for angular-jwt
    jwtOptionsProvider.config({
      tokenGetter: function() {
        return localStorage.getItem('id_token');
      },
      whiteListedDomains: ['localhost'],
      unauthenticatedRedirectPath: '/login'
    });
  }
})();




感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是我的坏事,您可以使用localStorage.getItem(' id_token')发送变量,并在app.js中直接使用

相关问题