Reputation: 867
I am new in angularJS, and I tried to make a service to handle HTTP requests.
So here is my service :
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) {
}
);
};
}
]);
And in my Chrome console I have this error which refers to the Authentification line :
TypeError: Cannot read property 'defaults' of undefined
I succeed to do my request without service, but impossible to reproduce with a service :(
Thanks for helping me
Upvotes: 0
Views: 24
Reputation: 692033
Change
this.getAllVideos = function($http, $base64) {
to
this.getAllVideos = function() {
You don't want to pass any argument when getting the videos. And the $http and $base64 services are injected in the service constructor function.
You also forgot to return from your function. Replace
$http({
by
return $http({
And once that is done, replace
$scope.data = HTTPrequest.getAllVideos();
by
HTTPrequest.getAllVideos().then(function(videos) {
$scope.data = videos;
});
You should also remove the empty eror callback from the $http call. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/, because you're falling into many promise traps.
Upvotes: 1