user5839 user5839 - 1 year ago 77
AngularJS Question

Right way of using Angular Factories and Services for this

I'm looking for a sensible way of doing this.. kind of learning Angular as I go and I've got a bit confused..

I have a service

.service('Cameras', function(Camera){
var _list = [];

// public API
this.list = _list;

document.body.addEventListener("dbready", function(){
for(var i=0; i < result.rows.length; i++)
_list.push(new Camera(result.rows.item(i).name, result.rows.item(i).ip, result.rows.item(i).id));
}, false);


Which is attempting to use this factory

.factory('Camera', function(name,ip,id) { = name;
this.ip = ip;
this.videoFiles = [];
this.photoFiles = [];
this.battery = 0; = 0;

To create the Camera objects.

I'm getting this error

[$injector:unpr] Unknown provider: nameProvider <- name <- Camera <- Cameras

Which I assume is because I;m not injecting the Camera factory into the Camera services properly - and I'm probably going about this the wrong way - but can anyone let me know the right way!?

Answer Source

No. You declared Camera as an Angular service.

The Camera service needs to be injected with the service 'name', the service 'ip' and the service 'id'. These services don't exist.

Remember that a service is a singleton. Their factory can take other services as arguments, but not data like a name, an ip or an id: where would Angular get these data when creating the unique Camera instance?

If you need such parameters to build a camera, then it shouldn't be a service at all. Just a regular JavaScript constructor function. And it should thus not be injected into the Cameras service.

Also note that the Camera doesn't do anything with the id passed as argument.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download