我正在学习有关 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);
有关更多详细信息,请阅读 this answer其中解释了服务和工厂是如何实现的。
关于javascript - Angular : how to retrieve a return value from a service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31637117/