AngularJS :如何从服务中检索 return 值

AngularJS : how to retrieve a return value from a service

我正在学习有关 Angular 服务的教程并测试下面提到的代码。我能够从像 -

这样的 TestService 获得视图中的值

TestService.name & TestService.$get()

但我想知道如果我需要从函数中获取返回值怎么办 - return "From myFun"+this.name; 在这种情况下。

代码-

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope, TestService){
    $scope.service = "Data From Service: "+TestService;
});

var myFun = function() {
    this.name = "FirstName";

    this.$get = function() {
        this.name = "Second Name";
        return "From $get: "+this.name;
    };

    return "From myFun"+this.name;
};

// A service returns an actual function
myApp.service('TestService', myFun);

Service

A service is a constructor function which creates the object using the new keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains method).

服务确实放置在 this 中,这是该服务的上下文,然后是 return 该上下文。

简单地说,您不能 return 反对服务,您可以使用工厂来做到这一点,因为工厂 return 和 object.

工厂

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope, TestService){
    $scope.service = "Data From Service: "+TestService;
});

var myFun = function() {
    var name = "FirstName";
    return "From myFun"+this.name;
};

// A service returns an actual function
myApp.factory('TestService', myFun);

但是在上面的例子中你一次只能return一个值,为了添加功能你需要修改你要从工厂return的对象。

修改工厂

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope, TestService) {
    $scope.service = "Data From Service: " + TestService;
});

var myFun = function() {
    var TestService = {};
    TestService.name = "FirstName";
    TestService.get = function() {
        TestService.name = "Second Name";
        return "From myFun" + TestService.name;
    };
};

// A service returns an actual function
myApp.factory('TestService', myFun);

Working Plunkr

有关详细信息,请阅读 this answer,其中解释了服务和工厂的实现方式。