Angular JS inject new instance of class

前端 未结 3 1307
情歌与酒
情歌与酒 2021-02-20 08:28

I want to inject instances of a class. From this thread it looks like services return new serviceArgFunction, which is what I want. https://groups.google.com/forum/#!msg/angul

相关标签:
3条回答
  • 2021-02-20 08:56

    Maximilian - thank you for the great example.

    I converted this to JSFiddle, as a place to experiment with another design pattern that I wanted to dig into. Why is it that swapping the provider type from "service" to "factory" still seems to work? It seems more about how the provider is created i.e. using 'new' versus just referencing it directly.

    Also, within the service, is there a design pattern as to why a service should implement the "this" keyword, as opposed to using using return { myAccessor : function () { return val; } }

    See http://jsfiddle.net/jeffsteinmetz/XF69p/

    In this jsfiddle, you can change one line of the code (line 23), and it still works, the line of code can be either:

    App.service('MyService', function() {
    

    or

    App.factory('MyService', function() {    
    

    Why do these both work?

    It seems more about how you reference the service with "new"

      var myInstance = new MyFactory();
    

    Which is different than just calling it directly

      MyService.getVal()
    

    Any angular folks care to lay out the best practices and reasoning behind this:

    • when to use 'new' and when you don't need new
    • why use the 'this' reference approach to define your provider instead of return { accessorName : function}
    • why do both factory or service work in the above example?
    0 讨论(0)
  • 2021-02-20 09:02

    To make it clear I created a little Plunker.

    It has a Service and a Factory. Service and Factory have a value and setters and getters.

    Both are injected into Controllers A and B. If You change the value of the Service in Controller A, this change takes also place in Controller B, because the service is a Singleton.

    But when You change the value in the Factory in the Controller B, this affects only B because the change takes only place in the instance that is created in B.

    Enjoy!

    0 讨论(0)
  • 2021-02-20 09:07

    You can use a factory that returns the constructor for your class:

    app.factory('myKlass', function() {
      return Klass
    });
    

    Even more simply, if Klass is defined elsewhere, you can use value:

    app.value('myKlass', Klass);
    

    Either way, inject it as normal.

    function CtrlA($scope, myKlass)
    {
      new myKlass();
    }
    

    See this jsFiddle.

    [Edit] See also this Google Groups post and this associated example.

    0 讨论(0)
提交回复
热议问题