javascript - Angular : how to retrieve a return value from a service

标签 javascript angularjs angularjs-service angularjs-factory

我正在学习有关 Angular 服务的教程并测试下面提到的代码。我能够从 TestService 中获取 View 中的值,例如 -

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 ,这是该服务的上下文,然后返回该上下文。

简单地说你不能从服务返回对象,你可以使用工厂来做到这一点,因为工厂确实返回一个对象

工厂

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);

但在上述情况下,您一次只能返回一个值,为了添加功能,您需要修改要从工厂返回的对象。

修改后的工厂

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其中解释了服务和工厂是如何实现的。

关于javascript - Angular : how to retrieve a return value from a service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31637117/

相关文章:

javascript - Shiny 应用程序可以在不访问服务器的情况下响应控件吗?

javascript - AngularJS ng-repeat 具有更好的性能 - 在 Controller 中重新分配值或过滤值

javascript - 不通过JSON获取kinetic js中的数据

javascript - Angular : Service variable changes not applying

javascript - 参数 'AppCtrl' 不是一个函数,未定义,似乎无法修复

angularjs - 尝试测试通用 angularjs $resource 服务时出现未知提供程序错误

javascript - var functionOne = (function(){})() 与 var functionTwo = (function(){}())

javascript - 过滤器不适用于函数返回值

javascript - 两个或多个功能的事件管理

javascript - 如何正确制作计数器 AngularJS