Angularjs来自工厂的对象

时间:2014-11-17 04:07:15

标签: javascript angularjs angular-promise

这里是我的Angularjs应用程序与coffeescript:

app.factory "User", ["$http", ($http ) ->
    current: ->
        $http.get("api/users").then (data) ->
            console.log(data.data)
    ]

app.controller "MainCtrl", MainCtrl = ["$scope", "User", ($scope, User) ->
    $scope.user = User.current()
    console.log($scope.user)
]

工厂退货承诺

Promise {$$ state:Object,then:function,catch:function,finally:function}

我需要从工厂返回一个对象:

对象{id:1,电子邮件:“example@example.com”,created_at:“2014-05-27T08:21:02.322 + 10:00”,updated_at:“2014-11-17T10:11:31.551+ 10:00“,客栈:”25“......}

我需要帮助。

1 个答案:

答案 0 :(得分:0)

尝试在您的服务中使用更具可读性的类方法:)

app.factory "User", ["$http", ($http ) -> 
    new class User
        constructor: ->
            @current()

        current: ->
            request = $http.get '/api/users'
            request.then (result) =>
                @user = result.data

]

现在,您将如何在控制器中获取数据

User.current().then (user) ->
    $scope.user = user