ReferenceError: angular is not defined? - javascript

I have create service that are interact with server side but my case error like
angular are not defined. I am tired this error.
(function() {
angular.module('myApp').factory('userService', function($http, $q, $rootScope,CONSTANTS) {
var obj = {};
var response = {};
obj.setResponse = function(data) {
response = data;
}
obj.getResponse = function() {
return response;
obj.saveUser = function(user) {
console.log(user);
console.log()
var deferred = $q.defer();
var config = {
headers : {
'Content-Type' : 'application/json'
}
}
var data = angular.toJson(user);
console.log(data);
$http.post("user/createUser", data, config).success(
function(data, status, headers, config) { deferred.resolve(data);
}).error(function(data, status, headers, config) {
deferred.reject();
});
return deferred.promise;
}
return obj;
});
})();

Related

Services in AngularJS with YoutubeAPI v3

I've used services once before (still not very good at it) and I've encountered a lot of issues already, so know I'm going to ask (I think my problem is easy AF:) )
I need to get some ChannelDetails with the use of YoutubeApi v3.
My Service:
appApi.factory('ServiceAPI', ['$http', function($http) {
var factory = {};
factory.channelDetails = function(channelname){
return $http.get('https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername='+channelname+'&key=AIzaSyDQv-WpATIWLinCB3H_sH4W1sKx7plyvRA')
.success(function(data) {
return data;
})
.error(function(data) {
return data;
});
}
}]);
then my controller:
var appApi = angular.module('YoutubeAPI', ['ngRoute'])
appApi.controller('youtubeCTRL', ['$scope','$http','$q','ServiceAPI', function ($scope, $http, $q, ServiceAPI) {
$scope.channel = [];
//GET Id on channelname
$scope.saveNewchlName = function () {
var channelname = $scope.newchlName;
$scope.channelDetails = function(channelname){
ServiceAPI.channelDetails(channelname).success(function (data) {
$scope.newchannelNames = {
channelName: $scope.newchlName,
channelId: data.items[0].id,
playlistId: data.items[0].contentDetails.relatedPlaylists.uploads
};
console.log($scope.newchannelNames)
$http({
method: 'POST',
url: 'http://localhost:8080/api/resources/channelNames/',
data: $scope.newchannelNames,
dataType: 'json'
}).success(function (data) {
$scope.channel.push(data);
console.log('SUCCESS!');
$scope.error = null;
}).error(function (data, status) {
if (status == 401) {
$scope.error = "You are not authenticated to Post these data";
return;
}
$scope.error = data;
});
});
}
}
My problem is that I keep encounter problems with injection. Now I got one which says: Provider 'ServiceAPI' must return a value from $get factory method.
I need to implement the channelname within the URL to get the specific details.
This seems to work.
Service:
appApi.factory('ServiceAPI', ['$http', function($http) {
var factory = {};
factory.channelDetails = function(channelname, success, error){
var promise = $http.get('https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername='+channelname+'&key=AIzaSyDQv-WpATIWLinCB3H_sH4W1sKx7plyvRA')
if(success){
promise.success(success);
}
if(error){
promise.error(error);
};
}
return factory;
}]);
controller:
var appApi = angular.module('YoutubeAPI', ['ngRoute'])
appApi.controller('youtubeCTRL', ['$scope','$http','$q','ServiceAPI', function ($scope, $http, $q, ServiceAPI) {
$scope.channel = [];
$scope.video = [];
var pagetokenarr = [];
//GET Id on channelname
$scope.saveNewchlName = function () {
var channelname = $scope.newchlName;
ServiceAPI.channelDetails(channelname, function(data){
$scope.newchannelNames = {
channelName: $scope.newchlName,
channelId: data.items[0].id,
playlistId: data.items[0].contentDetails.relatedPlaylists.uploads
};
console.log($scope.newchannelNames)
$http({
method: 'POST',
url: 'http://localhost:8080/api/resources/channelNames/',
data: $scope.newchannelNames,
dataType: 'json'
}).success(function (data) {
$scope.channel.push(data);
console.log('SUCCESS!');
$scope.error = null;
}).error(function (data, status) {
if (status == 401) {
$scope.error = "You are not authenticated to Post these data";
return;
}
$scope.error = data;
});
});
}

Can not read property then of undefined error in angular JS

This is my angularJS service and controller.
sampleApp.factory('BrandService', function($http, $q) {
var BrandService = {};
var BrandList = [];
BrandService.GetBrands = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: BrandURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( BrandList.length == 0 )
{
$http(req)
.success(function(response) {
BrandList = response.data
alert ('Brand Fetching is successful');
return response.data;
})
.error(function (data, status, headers, config) {
alert ('Brand Fetching Error');
alert (status);
alert (data);
});
}
else
{
var deferred = $q.defer();
deferred.resolve(BrandList);
return deferred.promise;
}
}
return BrandService;
});
sampleApp.controller('BrandController', ['$scope', 'BrandService', function ($scope, BrandService){
$scope.Brands = [];
$scope.GetBrands = function() {
BrandService.GetBrands().then(function(data) {
$scope.Brands = data;
});
};
$scope.GetBrands();
}]);
When controller is loading I m seeing the following error.
Cannot read property 'then' of undefined
at l.$scope.GetBrands (Controllers.js:337)
Can please someone help me what i m doing wrong?
You are not returning promise in case of HTTP request when data is not yet cached.
Correct code would be:
sampleApp.factory('BrandService', function($http, $q) {
var BrandService = {};
var BrandList = [];
BrandService.GetBrands = function() {
var req = {
url: BrandURL,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({Action: 'GET'})
};
if (BrandList.length) {
return $q.when(BrandList);
}
return $http(req)
.success(function(response) {
BrandList = response.data
alert('Brand Fetching is successful');
return response.data;
})
.error(function(data, status, headers, config) {
alert('Brand Fetching Error');
alert(status);
alert(data);
});
}
return BrandService;
});
Also you don't need to create dummy deferred object, you can return resolved promise with $q.when.

Connecting a promise through two services

I'm a bit new to angular and am trying to understand how I can use a promise with two services.
In the code below in the App.js I call FirstService.get(), which should wait for the RestService to return the result. In the App.js I would like to use the .then() to wait for the result from FirstService.get().
My question how do I need to set up the promise in the First Service so that I can use the .then() in the App.js?
Thanks!
// App.js
FirstService.get().then(function(promise) {
// do something here with the result
}, function(response) {
console.log('error');
});
//First Service
oApp.service( 'FirstService', function( RestService, $localStorage, $q ) {
this.get = function( ) {
var url = o.buildServerUrl();
// Retrieve info
RestService.get(url, function(response) {
return response;
});
};
});
// Rest Service
oApp.service( 'RestService', function( $rootScope, $http ) {
this.get = function ( url, callback ) {
try {
$http.get(url).
success(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
}).
error(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
});
}
catch(err) {
var response = o.createExceptionResponse(err.message);
callback(response);
}
}
});
This should do it:
// App.js
FirstService.get().then(function(promise) {
// do something here with the result
}, function(response) {
console.log('error');
});
//First Service
oApp.service( 'FirstService', function( RestService, $localStorage, $q ) {
this.get = function( ) {
var deferred = $q.defer();
var url = o.buildServerUrl();
// Retrieve info
RestService.get(url, function(response) {
deferred.resolve(response);
});
return deferred.promise;
};
});
// Rest Service
oApp.service( 'RestService', function( $rootScope, $http ) {
this.get = function ( url, callback ) {
try {
$http.get(url).
success(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
}).
error(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
});
}
catch(err) {
var response = o.createExceptionResponse(err.message);
callback(response);
}
}
});

How to returning data from a resource using angular

I'm creating service layers to interact with Rest server, but I've got some problems with ngResource promises.
var grupogestion= angular.module('app.grupogestion.services', ['ngResource']);
grupogestion.factory('Grupogestion', ['$resource', function ($resource){
return $resource('api/grupogestiones/:action/:id.:format',
{
action: '#action', id:'#id', format:'json'
},
{
'get': {method:'GET'},
'post': {method:'POST',headers : {'Content-Type': 'application/x-www-form-urlencoded'}},
'save': {method: 'POST',headers : {'Content-Type': 'application/x-www-form-urlencoded'}}
}
);
}]);
grupogestion.service('GrupogestionService',['Grupogestion', function (Grupogestion){
this.findAll = function (){
Grupogestion.get({action: 'index'},function (data, status, headers, config){
return data;
});
}
this.save = function (grupogestion){
Grupogestion.save({'action':'add'},$.param(grupogestion)).$promise.then(
function(data){
alert('k');
return data;
},
function(error){
alert('j');
return error;
}
);
}
}]);
When I call var response = GrupogestionService.save(data) from angular controller, I don't get the data at the same time I call the function, so the question is: How can I modify GrupogestionService for returning data to the controller?
I've tried to return the promise but I couldn't do it. Thanks for helping.
// service code
grupogestion.service('GrupogestionService', ['Grupogestion', function (Grupogestion) {
this.findAll = function () {
Grupogestion.get({action: 'index'}, function (data, status, headers, config) {
return data;
});
};
this.save = function (grupogestion) {
return Grupogestion.save({'action': 'add'}, $.param(grupogestion));
}
}]);
//run in your controller
var response = GrupogestionService.save(data).$promise.then(
function (data) {
alert('k');
return data;
},
function (error) {
alert('j');
return error;
}
);

Pass data from service to controller in angularjs

Following is my Service code -
myApp.service('loginServiceChk', function(){
this.getInfo = {};
this.chkLogin = function($http,$location,$window){
$http.get('/users/chklogin')
.success(function (data, status, headers, config) {
if (data.code!="200"){
this.getInfo = {};
$window.location.href='/#/users/login';
}else{
this.getInfo = data.usersession;
}
});
};
});
My controller code -
myApp.controller('userDash',function($scope,$http,$location,loginServiceChk,$window){
loginServiceChk.chkLogin($http,$location,$window);
console.log(loginService.getInfo);
$scope.userLogout = function() {
$http.get('/users/logout').success(function (data, status, headers, config) {
if (data.logout=="200"){
merInfo = {} ;
$window.location.href='/#/userss/login';
}
})
};
});
However I am always getting an empty object in the console ( console.log(loginService.getInfo); ) . Let me know what I am doing wrong here.
I am expecting session data in the this.getInfo.
EDIT
If I am using .then then it is going in the if ie if (data.code!="200"){ here.
You have to wait for the promise.
Use this in your controller:
loginServiceChk.chkLogin($http,$location,$window).then(function() {
console.log(loginService.getInfo);
});
And add return to your service:
this.chkLogin = function($http,$location,$window){
return $http.get('/users/chklogin')
.then(function (data, status, headers, config) {
if (data.code!="200"){
this.getInfo = {};
$window.location.href='/#/users/login';
}else{
this.getInfo = data.usersession;
}
});
};

Categories

Resources