Service nie zwraca danych

0

Witam,
Mam taki problem, że serwis nie zwraca danych, w serwisie dane są, ale w kontrolerze ich brak. Jak zwrócić poprawnie odpowiedź, żeby było widać ją w kontrolerze w zmiennej $scope.phone.

angular.module('phonesApp').service('PhoneService', function($http, $resource) {
    /*
     data – {string|Object} – The response body transformed with the transform functions.
     status – {number} – HTTP status code of the response.
     headers – {function([headerName])} – Header getter function.
     config – {Object} – The configuration object that was used to generate the request.
     statusText – {string} – HTTP status text of the response.
     */
    this.findOnePhone = function(id) {
        var url = 'api/phone/id/' + id;
        $http({
            method : "GET",
            url : url
        }).then(function successCallback(response) {
            //alert(angular.toJson(response.data)); //są dane
            return response.data;
        }, function errorCallback(response) {
            return response.status;
        });
    }

    this.method2 = function() {
        //..
    }
});


angular.module('phonesApp').controller('DetailPhoneController', function ($scope, $http, $routeParams, $rootScope, PhoneService) {
    $scope.message = 'Telefony';
    $scope.phone='';

    var loadPhoneData = function (id) {
        $scope.phone = PhoneService.findOnePhone(id);
    }
    loadPhoneData($routeParams.id);

});
1

Przecież nic nie zwracasz z metody findOnePhone, to co ma się zadziać? Zwróć promisa to będziesz go mógł potem uzyć.

angular.module('phonesApp').service('PhoneService', function($http, $resource) {
  // ...
    this.findOnePhone = function(id) {
        var url = 'api/phone/id/' + id;
        return $http({
            method : "GET",
            url : url
        }).then(function successCallback(response) {
            return angular.toJson(response.data);
        }, function errorCallback(response) {
            return response.status;
        });
    }
  // ...
});
 
angular.module('phonesApp').controller('DetailPhoneController', function ($scope, $http, $routeParams, $rootScope, PhoneService) {
  PhoneService
    .findOnePhone(id)
    .then(console.log)
});
0

Można dodać, że preferowana wersja to wersja z łączeniem promisów

callback version, usunięta w wersji 1.6

$http.get("...")
  .then(successHandler, errorHandler);

preferowana wersja

$http.get("...")
  .then(successHandler1)
  .then(successHandler2)
  .catch(errorHandler);

1 użytkowników online, w tym zalogowanych: 0, gości: 1