$http Angularjs Return not expected

Asked

Viewed 90 times

2

Description

I am implementing a $http request with angular. I want to return the database objects.

Code

Companyservice.coffee

angular.module('vaultfactor').factory 'CompanyService', ($http, $q) ->
getCompanies: ->
    promise = $http.get "/companies"
    company = promise.then((response)->
        if typeof response.data == 'object'
            console.log(response.data)
            return response.data
        else
            return $q.reject(response.data)
    (response)->
        $q.reject(response.data))

main_ctrl.coffee

angular.module('vaultfactor').controller 'HomeCtrl', ($scope, $rootScope, 
    $location, $http, CompanyService) ->
        console.log(CompanyService.getCompanies())

Problem

The returned object is not the model you expected. inserir a descrição da imagem aqui

Giving a console.log to my sponse.date. before Return it returns me exactly what I need. like this: ( Being passed in dependencies $q, I posted an older image. )

inserir a descrição da imagem aqui

Console.log:

inserir a descrição da imagem aqui

What I’m going through wrong in my Success’s Return?

1 answer

2


Try this way in service:

angular.module('vaultfactor').factory 'CompanyService', ($http, $q) ->
getCompanies: ->
    $http.get "/companies"

And where to use the list:

angular.module('vaultfactor').controller 'HomeCtrl', ($scope, $rootScope, 
    $location, $http, CompanyService) ->
        promise = CompanyService.getCompanies()
        company = promise.then((response)->
            if typeof response.data == 'object'
                console.log(response.data)
                return response.data
            else
                return $q.reject(response.data)

Remember that this works if the return is an object, if it is an array you need to replace get by query as in the example below:

$http.query "/companies"
  • I work perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.