javascript - AngularJS learning about services and factories, a service in a factory? -


Before I revisit a large project, I really want to build Angular's service / factory / provider I am trying to wrap my head in / P>

I've read about lots of services and factories on documents and articles I thought about how each of them is made and what they do.

However, while trying stuff, I tried to use a service in a factory or two ...

It was really useful: now I think that my Just 'jsonService' (this is a singleton), so this simple approach will not work ... (I need some factory which is a different example of something)

  .ervice ( 'Jsonservice', ['$ http', function ($ HTP) {var data = {'msg': 'no data'}; this.serviceData = data; this.get = function (url) {$ http.get (Url). Then (function (resp ) {Data = resp.Data;});}}]) .Feature ('FAP1', ['Jason's', Function (JasonAssis) {jsonService.get ('json / data1.json'); Then turn jsonService. ServiceData;}]).) () '' FAP '', ['Jason's', function (JSONSearer) {JSNSRVG.GATE ('Jason / Data 2.Jesen'); Jason's service;}])  

When I use factories like a controller:

  myController.f1 = fac1; MyController.f2 = fac2.serviceData;  

I can see that fac1 and fac2 return both objects, they both {msg: 'somebody Data is not '} , if I change one, they both make changes.

My question is:

However, I can break the service and data = {Msg: 'no data'} Setting - Why do not I see any changes in fac1 or fac2 ?

I think there should be more than one var data , something is not a 'singleton' ????

Edit: Now I tried:

  this.serviceData = function () {return data;};  

and:

  myController.f2 = fac2.serviceData (); // It is not always a 'data' object myController.f3 = fac2.serviceData;  

If I (after long) call:

  var something = myController.f3 ();  

Then I get JSN data ... but myController.f2 still {msg: 'no data'} Why?

OK, after taking the suggestion of McNrowroy, Detected ...

The problem is nothing to do with angular, how it passes through javascript objects (see :)

The factories have the original {msg: 'No data'} returned a 'per-context' of the object, and when the service was finally assigned:

  data = resp.data;  

That replaced 'data', but factory-provided references continue as old objects.

Now, if I do: / P>

  .service ('jsonService', ['$ http', function ($ http) {var data = {'msg': 'No data', 'result': zero); ServiceData = data; This.get = function (url) {$ http.get (url). Then (function) {data.result = resp.data; // Update properties of data object data. .msg = 'found 

variable in myController

Obviously, I still have problems that my two factories same thing ( I will look at Sacho's suggestion on this) - but I think I have learned something very basic here.


Comments