【问题标题】:Is there anyway to create Javascript object with "default function"? AngularJS有没有用“默认函数”创建Javascript对象? AngularJS
【发布时间】:2016-02-25 08:04:55
【问题描述】:

您可能知道,AngularJS $http 服务允许使用/不使用特定功能来调用它,例如:

  1. $http(req).then(function(){...}, function(){...});

  2. $http.get('/someUrl', config).then(successCallback, errorCallback);

我想了解更多关于如何在我的工厂以及通常在 JS 中实现它的方式。

【问题讨论】:

  • 如果问题更多关于如何架构角度数据检索 - 检查 $resource - docs.angularjs.org/api/ngResource/service/$resource
  • 对我来说,这似乎更像是您在询问如何实现回调。你问的是这个吗?
  • @dvir 谢谢,我得到了 Shreyas 的回答

标签: javascript angularjs function object


【解决方案1】:

正如上面提到的,你可以使用 Angular 的“$resource”来实现你想要的。这是一个如何使用它的示例:

app.service('testResource', ['$resource',  function ($resource) {
    var apiBaseUrl = 'http://test-backend/api';
    var testResource = $resource(
        apiBaseUrl + '/test/'
        {},
        {
            'query': {
                method: 'GET',
                isArray: true
            }
        }
    );
    this.getAll = function () {
        return testResource
            .query()
            .$promise
            .then(function (data) {
                var tests = [];
                angular.forEach(data[0], function (value) {
                    tests.push(value);
                });
                return tests;
            });
    };
}]);

然后将其注入 Controller(或任何地方)并调用它:

testResource.getAll().then(
                        function (data) {
                            $scope.tests = data;
                        }
                    );

您还可以实现其他方法,例如 POST、PUT、DELETE。

【讨论】:

    【解决方案2】:

    函数是 JavaScript 中的对象。这意味着您可以在函数上分配其他属性和函数。

    function foo(){
       //do something
    }
    
    foo.bar = function(){
       //do something else
    }
    

    【讨论】:

    • 非常感谢!有道理。 z0r 示例:var a = function(){ alert('main'); } a.foo = function(){ alert('bar'); } a(); a.foo();
    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2018-04-18
    相关资源
    最近更新 更多