简体   繁体   中英

How to inject a third party library to an angular.js service

I am having trouble while trying to load the angular-cache library to my service. I used bower to add angular-cache to my project and it is successfully added. When I debug the service code on Chrome I see in the "Networks" tab that angular-cache is loaded:

Name: angular-cache.js
Method: GET
Status: 200
Type: script
Initiator: require.js:1901
Size: 6,5 kb
Time: 16 ms

There is a config.js file that I load all my libraries. This line is for angular-cache:

'angular-cache': '../bower_components/angular-cache/dist/angular-cache',

and this is the line inside shim:

'angular-cache': ['angular'],

And this is the service:

 define(
    [ 'angular', 'services-module'],
    function(angular, services) {
        services.factory(
          'MyService',
           [
            "$location",
            "$interval",
            "MyOtherService",
            "CacheFactory",
            function($location, $interval, otherService, cacheFactory) {

               var service = {
                    myCachingFunction : function(parameters){

                    }, 
                    getCache : function(cacheId) {

                    }
                }
                return service;
            } ]);
});

This is the error I get:

Error: [$injector:unpr] Unknown provider: CacheFactoryProvider

This is the github page of the angular-cache. What am I missing?

Have you tried this, I guess that this is your service.js:

define(
['angular', 'services-module'],
function(angular, services) {
    services.factory(
      'MyService',
       [
        "$location",
        "$interval",
        "MyOtherService",
        "CacheFactory",
        function($location, $interval, otherService, cacheFactory) {

In your app.js:

define(
['angular', 'angular-cache'],
function(angular) {
    var myApp = angular.module('myApp', [ 'ngResource', 'app.controllers', 'app.directives', 'app.services', 'app.filters', 'app.routes', 'app.interceptors', 'angular-cache' ]);

In config.js:

    shim: {
      'angular-cache': {
         deps: ['angular']
       }
    }

I'm guessing that you are using Require with Angular.

You want to include is as a module like this:

define(
    [ 'angular', 'services-module', 'angular-cache'],
    function(angular, services, cache) {
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM