I have a set of angular $resource
defined in a module called 'App.API' in a single file which I cannot touch because it is generated. (With loopback-angular
, a tool to generate angular $resource from server side model definitions)
Let's take the Product
dependency as en example, later in the app, I want to override its prototype, like this :
module('App.NewModule', ['App.API']).run(['Product', function(Product) {
Product.prototype.getTitle = function() {
return 'Product name is ' + this.name;
};
// From now on I can use p.getTitle() on every Product $resource
});
It works.
The thing is, I have many different files, each containing modules, and I am experiencing a dependency injection issue : I can access the getTitle
function inside NewModule
, but not inside other modules .
Question : How can I override a dependency object prototype and make it available to other modules ?
I tried to define the prototype functions in this way instead, thinking that Product
prototype would be modified. Maybe not early enough :
module('App.API').run(['Product', function(Product) {
Product.prototype.getTitle = function() {
return 'Product name is ' + this.name;
};
});
It does not work : using getTitle
in another module (using App.API/Product as a dependency) on a Product
instance still throws a undefined is not a function
error, even while Product
object is correctly injected.
Actually, I just messed up the dependency definitions / orders.
I have three files :
app.js
for module App
(dependant on module App.API
) api.js
for module App.API
product.js
containing Product
prototype As stated in the question, I was doing :
// in product.js
module('App.API').run(['Product', function(Product) { ... }]);
// in app.js
var appModule = module('App', ['App.API']);
But the App.API
module was defined in another file, which is a bit messed up because you never know for sure which one will load first, unless dealing with in in the js loader and loosing parallel downloads.
So I explicitly specified the modules and dependencies, at the expense of adding more dependency to declare in my app (but it works and is more stable) :
// in product.js
module('ApiProduct', ['App.API']).run(['Product', function(Product) { ... }]);
// in app.js
var appModule = module('App', ['App.API', 'ApiProduct']);
Note : In my first attempt, I defined the prototype in a new module in a .config()
block, but it was not working, maybe because App.API
services were not loaded yet. With .run()
it works and my getTitle
prototype is available everywhere I need Product
provider.
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.