Monday 15 June 2015

javascript - How to inject service from external file using AngularJS and RequireJS? -



javascript - How to inject service from external file using AngularJS and RequireJS? -

i'm injecting controller external file , want same thing service external file. should registered in mill statement.

injecting of controller working

controllers

'use strict'; define(['angular', 'services'], function (angular) { homecoming angular.module('vcapp.controllers', ['vcapp.services']) .controller('authctrl', ['$scope', '$injector','authservice', function($scope, $injector, authservice) { require(['auth/authctrl'], function(authctrl) { $injector.invoke(authctrl, this, {'$scope': $scope, 'authservice':authservice}); }); }]); });

authctrl

define([], function() { homecoming ['$scope', '$routeparams', '$location', '$http', 'authservice', function($scope, $routeparams, $location, $http, authservice) { $scope.signin = function() { ... } $scope.$apply(); }]; });

and want inject service

services

'use strict'; define(['angular'], function (angular) { angular.module('vcapp.services', []) .factory('authservice', ['$http', '$injector', function($http, $injector) { require(['auth/authservice'], function(authservice) { $injector.invoke(authservice, this, {'$http': $http}); }); }]); });

authservice

define([], function() { homecoming ['$http', function ($http) { homecoming { login: login }; function login(username, password) { var request = $http(...); return(request); } }] });

when authcontroller calls authservice.login(...), throws error error: [$injector:undef] provider 'authservice' must homecoming value $get mill method..

this code inspired angular-requirejs-seed project.

as says, angular's factory() expected homecoming service object. may have luck like:

define(['angular'], function (angular) { angular.module('vcapp.services', []) .factory('authservice', ['$http', '$injector', function($http, $injector) { var stub = {}; require(['auth/authservice'], function(authservice) { angular.extend(stub, $injector.invoke(authservice, this, {'$http': $http})); }); homecoming stub; }]); });

here define stub service , extend it, when service lazy-loaded.

(by way think lastly 2 arguments of $injector.invoke() redundant in case.)

if want thought mixing requirejs , angular, plays lazy loading , r.js optimizer, may take @ angular-require-lazy.

javascript angularjs dependency-injection requirejs

No comments:

Post a Comment