在angularJS

时间:2016-02-24 23:00:04

标签: angularjs rest http service

我是angularJS的新手,我试图提供服务来处理HTTP请求。

所以这是我的服务:

var app = angular.module("myApp", ['base64']);

/* Main controller
================================================== */

app.controller("MainCtrl", ["$scope", "HTTPrequest",
    function($scope, HTTPrequest) {
        $scope.data = HTTPrequest.getAllVideos();
    }
]);

/* Service which handles HTTP requests
================================================== */

app.service("HTTPrequest", [ "$http", "$base64",
    function($http, $base64) {

        //Getter pour la variable videos
        this.getAllVideos = function($http, $base64) {

            // Authentification for HTTP request on RESTHeart server
            $http.defaults.headers.common["Authorization"] = 'Basic ' + $base64.encode("LOGIN" + ":" + "PASSWORD");

            $http({
              method: 'GET',
              url: 'http://localhost/db/videos',
            }).then(
                function successCallback(response) {
                var videos = response.data;
                return videos;
                },
                function errorCallback(response) {

                }
              );

        };

    }
]);

在我的Chrome控制台中,我有这个错误,它引用了身份验证行:

  

TypeError:无法读取未定义

的属性'defaults'

我在没有服务的情况下成功完成了我的请求,但无法通过服务重现:(

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

更改

this.getAllVideos = function($http, $base64) {

this.getAllVideos = function() {

获取视频时,您不想传递任何争论。并且$ http和$ base64服务被注入服务构造函数。

你也忘记了从你的功能回来。取代

$http({

通过

return $http({

一旦完成,请替换

$scope.data = HTTPrequest.getAllVideos();

通过

HTTPrequest.getAllVideos().then(function(videos) {
    $scope.data = videos;
});

您还应该从$ http调用中删除空的eror回调。阅读http://blog.ninja-squad.com/2015/05/28/angularjs-promises/,因为您正陷入许多承诺陷阱。