How can I test an AngularJS service from the console?

前端 未结 4 1349
滥情空心
滥情空心 2020-11-29 14:06

I have a service like:

angular.module(\'app\').factory(\'ExampleService\', function(){
  this.f1 = function(world){
    return \'Hello \'+world;
  }
  return         


        
4条回答
  •  情话喂你
    2020-11-29 15:00

    First of all, a modified version of your service.

    a )

    var app = angular.module('app',[]);
    
    app.factory('ExampleService',function(){
        return {
            f1 : function(world){
                return 'Hello' + world;
            }
        };
    });
    

    This returns an object, nothing to new here.

    Now the way to get this from the console is

    b )

    var $inj = angular.injector(['app']);
    var serv = $inj.get('ExampleService');
    serv.f1("World");
    

    c )

    One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do

    app.factory('ExampleService',function(){
            return function(){
                this.f1 = function(world){
                    return 'Hello' + world;
                }
            };
        });
    

    This returns an ExampleService constructor which you will next have to do a 'new' on.

    Or alternatively,

    app.service('ExampleService',function(){
                this.f1 = function(world){
                    return 'Hello' + world;
                };
        });
    

    This returns new ExampleService() on injection.

提交回复
热议问题