ngResource query returns strange objects - javascript

I am new to AngularJS and wanted to try out the $resource functionality.
I have this code:
.factory('GetTasksService', function($resource, BASE_URL) {
return $resource(BASE_URL + 'api/tasks');
})
.controller('TasksCtrl', function ($scope, $http, BASE_URL, GetTasksService) {
$scope.tasks = GetTasksService.query();
$scope.getTasks = function () {
$http({ url: BASE_URL + 'api/tasks', method: 'GET' })
.success(function (data, status, headers, config) {
$scope.tasks = data;
})
.error(function (data, status, headers, config) {
alert("call did not work");
});
}
});
The getTasks function works as expected - returning an array of:["taska", "taskb"] as it should.
The GetTasksService.query() however returns an array of [{"0":"t","1":"a","2":"s","3":"k","4":"a"}, {"0":"t","1":"a","2":"s","3":"k","4":"b"}]
Can anyone tell me what I am doing wrong?

There is an option when specifying an action for an ngResource called isArray;
The default action query sets this as true by default, so you need to set set the action like:
query : {
method : 'GET',
isArray : false
}

Related

AngularJS : Injecting Service in app.run

I want to initialize a globle variable "$rootScope.SegmentSelectedGlobal" at the starting of application only.
This globle variable get data from a service.
If i execute service through controller, its working fine.
But when i execute it from App.run, no value is being assinged an d no error is being reported.
Here is the code:
App.run :
app.run(['$rootScope','DashboardService', function($rootScope,DashboardService) {
$rootScope.SegmentSelectedGlobal = DashboardService.getSegments();
}]);
Service :
app.service("DashboardService",function($q,$http,errorMessages){
var allSegements = [];
return {
// For selected Only
getSegments : getSegments
}
function getSegments(){
var deferred = $q.defer();
$http({
url: "/getAllSegments",
method: "GET"
}).success(function (data, status, headers, config) {
deferred.resolve(data);
allSegements = data;
}).error(function (data, status, headers, config) {
//logger.logError('Error while retrieving Versions details');
allSegements = null;
});
return allSegements;
}
});
Thanx for your help.
It returns undefined because at return allSegements allSegements is undefined.
Your using a promise, yet your forgot to return it properly
app.service("DashboardService",function($q,$http,errorMessages){
var allSegements = [];
return {
// For selected Only
getSegments : getSegments
}
function getSegments(){
var deferred = $q.defer();
$http({
url: "/getAllSegments",
method: "GET"
}).success(function (data, status, headers, config) {
deferred.resolve(data);
allSegements = data;
}).error(function (data, status, headers, config) {
//logger.logError('Error while retrieving Versions details');
deferred.reject();//--------- REJECT IF ERROR
});
return deferred.promise;//------- RETURN THE PROMISE
}
});
app.run(['$rootScope','DashboardService',function($rootScope,DashboardService) {
// use then to get the data from your promise ince it's ready
DashboardService.getSegments().then(function(data){
$rootScope.SegmentSelectedGlobal = data;
});
}]);
Note if you want to wait for the promised to be resolved before loading your page, use the resolve attribute (available in both ngRoute/ui-router) :
resolve:{
segments:['DashboardService', function(DashboardService){
return DashboardService.getSegments();//we return the promise, the resolve parameter will take the result, in case of error page won't be loaded.
}];
}

how to call $scope.function1 from $scope.function2

I have a controller with the two functions.function "fileHistory" will be loaded first.
and i need to same call the same function from another function success callback.
i tried this way- but i am getting error
here is my Controller code
function cBookController($scope,$http) {
$scope.fileHistory = function() {
$http({
url: '/123/rest/getUploadDetails',
method: "GET"
})
.success(function (data, status) {
console.log(data);
$scope.fileHistory = data;
})
.error(function (data, status) {
alert("Error in get history details process");
});
}
$scope.fileHistory();
$scope.checkStatus = function(uploadedFileId) {
$http({
method: 'GET',
url: '/123/rest/checkStatus',
})
.success(function(data, status, headers, config) {
//here i need to get the new datafrom fileHistory service.
$scope.fileHistory();
})
}
}
By checking in your code I see that inside the $http success callback of fileHistory function, you override your function with response data from $http
Your fileHistory is a function at first. But after your promise is executed you are assigning this to a data variable and overriding it.
Change following line to something else -
//$scope.fileHistory = data; // change this line
$scope.fileHistoryData = data;

AngularJS - Dealing with properties file

I'm trying to read a properties file in angular, It's neccesary to have this file at the root of my project without any kind of angular stuffs, just a simple file, like java.
This is what I'm doing.
Creating a angular.properties file.
angular.properties
{
"url": "http://localhost"
}
This is my controller where I invoke my service method:
controller
captchaService
.all()
.then(function(data) {
...
}, function (data) {
...
});
This is my service class:
service
'use strict';
angular.module('app.service', [])
.factory('myService',
['$http', '$q',
function ($http, $q) {
var _URL = "";
function getValuesFromProperties() {
$http({
method : 'GET',
url : 'angular.properties'
}).success(function (data, status, headers, config) {
_URL = data.url;
}).error(function (data, status, headers, config) {
...
});
}
function all() {
getValuesFromProperties();
var deferred = $q.defer(),
promise = deferred.promise;
sessionStorage.removeItem('X_CAPTCHA_TOKEN');
$http({
method : 'POST',
url : _URL
}).success(function (data, status, headers, config) {
...
}).error(function (data, status, headers, config) {
...
});
return promise;
}
return {
all : all,
getValuesFromProperties : getValuesFromProperties
};
}]);
But here in my services class I have two $http running on an asynchronous way for that reason I can not get the value of url everything else works perfect. How can resolve this? Maybe there is another way to do this. I don't want to create a constant class because this file it's placed at the root of the project and it will be configure for others, they don't need to enter inside a lot of folders and check the code, search and edit. Any idea?

how to convert AJAX $http call to Angular.JS

For a functionality that I need, I found a really nice AJAX example. Basically it calls the Yahoo API. But I'm working with Angular.JS. So I have no clue how to convert that. Any help?
That's the AJAX function (details see this posting and this JsFiddle):
$.ajax({
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
data:{
query: request.term
},
url: 'http://autoc.finance.yahoo.com/autoc',
success: function (data) {
alert("yes");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
So what I'm looking for, is how to convert the code above into somewhat like this. The sample should just print the return value. See this JsFiddle. Especially, I have not idea what to do with the jsonpCallback parameter. That's what I could not find in any other example.
<div ng-app='MyModule' ng-controller='DefaultCtrl'>
{{ test() }}
</div>
JavaScript
function DefaultCtrl($scope, myService) {
$scope.test = myService.test;
}
angular.module('MyModule', [])
.factory('myService', function () {
return {
test: function () {
$http.get("?????")
.success(function(data, status, headers, config) {
return data;
})
.error(function(data, status, headers, config) {
return "there was an error";
})
}
}
});
The intermediate solution - after all your help - looks like this. Thanks. I had to install a Chrome extension which allows cross-domain calls as long as you use the updated JsFiddle. I changed the way I'm passing the parameters to the http-get call and I also included the $q (promise) handling. The result contains a valid list from Yahoo YQL API. Just need to handle that array then.
function DefaultCtrl($log, $scope, $http, myService) {
var promise = myService.getSuggestions('yahoo');
promise.then(
function(payload) {
$scope.test = payload;
$log.info('received data', payload);
},
function(errorPayload) {
$log.error('failure loading suggestions', errorPayload);
});
}
angular.module('MyModule', [])
.factory('myService', function ($http, $log, $q) {
return {
getSuggestions: function (symbol) {
var deferred = $q.defer();
$http.get('http://d.yimg.com/autoc.finance.yahoo.com/autoc', {
cache: true,
params: {
query: symbol,
callback: 'YAHOO.Finance.SymbolSuggest.ssCallback'
}
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
return deferred.promise;
}
}
});
just have a look at the docs
https://docs.angularjs.org/api/ng/service/$http
$http.get('http://autoc.finance.yahoo.com/autoc',
{dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback'}).success(function(data){ alert("yes"); });
Use Ajax call and you have to use promise
And use only test not {{test()}}
Because in your controller when you call your factory ajax function then in controller you get undefined response.
So use promise.
Service:
var demoService = angular.module('demoService', [])
.service('myService',['$http', function($http) {
this.getdata = function(entity){
var promise = $http({
method : 'GET',
url : 'services/entity/add',
data : entity,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
headers : {
'Content-Type' : 'application/json'
},
cache : false
}).then(function (response) {
return response;
});
return promise;
};
}]);
Controller :
var demoService = angular.module('demoService', [])
.controller('myctr',['$scope','myService',function($scope,myService){
myService.getdata().then(function(response){
//Success
},function(response){
//Error
});
}]);
now you can see your json in controller success

not getting data from $http from service to scope

we are trying to get data from service agrService with $http its working but when i reccive data to controller i am not able to access it outside that function
$scope.resource return data inside function but not outside please help.
var app = angular.module('app', ['ui.router','ngTasty']);
app.config(['$urlRouterProvider', '$stateProvider',function($urlRouterProvider, $stateProvider, $routeProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html',
controller: function($scope, $http, $location, agrService) {
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
}, function(error) {
// do something else
});
I NEED TO ACCCESS DATA HERE CAN ANY BODY HELP
console.log($scope.resource);
}
});
}]);
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
var ret = $q.defer();
$http({
method: 'GET',
dataType: "json",
url: dataUrl
})
.success(function(data, status, headers, config) {
ret.resolve(data);
}).error(function(data, status, headers, config) {
ret.reject("Niente, Nada, Caput");
});
return ret.promise;
};
});
My suggestion would be to rethink the logic a bit. You want to do something with the data after you receive it, so why not make a function that you call once the data is received?
You'll never be able to access the resource data in that console log, simply because $http is an async call, and no matter if you return a promise or not, it's simply not ready at that point.
However, if you use it in a template or elsewhere that uses angular's double binding, it will work just fine.
To fix your issue, you can define a function with what happens after that service call and simply call it from the success callback:
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
myAfterFunction(); // <--- here
}, function(error) {
// do something else
});
and the function can be:
function myAfterFunction() {
console.log($scope.resource);
}
And btw. your service is an example of deferred antipattern, you can simply do this:
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
return $http({
method: 'GET',
dataType: "json",
url: dataUrl
})
};
});

Categories