How to get json data in my case? - javascript

I am trying to use httml get to get the json
I have something like
.controller('testController', function($scope, $state, $http) {
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
console.log(data)
});
//outside of the $http scope but under the same controller, I have
//It shows undefined.
console.log($scope.testData)
})
I know we have to keep data our of the login codes so I don't want to modify the data inside the $http. Is there anyway to accomplish this? Thanks!

First, don't put this in a controller. Move it to a Service. That's what Services are designed for.
Second, the $http service is asynchronous. Your result only exists in the success callback, and your console.log will be called before the http request is finished. You need to assign it to a scope variable to use it outside of the callback, and expect it to be empty until the call back is complete.
http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app provides an example of an AngularJS authentication service, if that's what you're doing.
To go with your example:
.controller('testController', function($scope, $state, $http) {
$scope.testData = {};
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
$scope.logData();
});
$scope.logData = function() {
console.log($scope.testData);
}
});

This plnkr code is created in order to give your answer, yes you can have the $scope.testData outside the http request.
Have a look!!
var app = angular.module('plunker', []);
app.controller('testController', function($scope, $http) {
$http({
url: "test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
alert(data);
callA();
});
function callA(){
alert($scope.testData);
}
});

Related

How to acces XML data in response

I have this method
angular.module('RDash')
.controller("SipsCtrl", ['$scope','$http', function($scope, $http){
'use strict';
$http({
method: 'GET',
url: 'http://192.168.2.35/SIPSWS/SIPSWS.asmx/HelloWorld'
}).then(
//OK
function (response) {
$scope.btnCUPS = "Exito",
},
//KO
function (response) {
$scope.btnCUPS = "Error",
});
}]);
I have a server status 200 ok, but y donĀ“t see the response.
I should receive XML data response with the next structure
<string xmlns="http://tempuri.org/">Hola a todos</string>
How can I put de response in my view?
See if you are really getting the data by: console.log(response);
If you are, the generaly comes a data inside response, in the controller:
$scope.data = response.data;
In the view:
<div>{{data}}</div>

Passing information previously retrieved to templateProvider in AngularJS

I'm using AngularJS 1.3 and UI-Router. I have an state in which i have a resolve and a templateProvider.
What i'm trying to accomplish is that the information retrieved from database in the resolve can be used by the templateProvider. Right now, I have to get the information twice, once from resolve and another from templateProvider, and that's annoying.
The code:
.state('articleurl', {
url: '/:articleUrl',
resolve: {
article: function ($http, $stateParams, $location) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
})
.then(function (article) {
return article;
}, function (error) {
$location.path('/404');
});
},
loggedin: checkLoggedin
},
templateProvider: ['$templateFactory', '$stateParams', '$http', function ($templateFactory, $stateParams, $http) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
}).then(function(article) {
if ( article.data.template )
return $templateFactory.fromUrl('articles/views/templates/' + article.data.template + '.html');
else
return $templateFactory.fromUrl('articles/views/templates/news.html');
});
}],
controller: 'ArticlesViewController'
})
As you can see, according to article's kind i load a different template in the templateProvider. Besides, i use the article's information in the controller which has been previously got in the state's resolve.
Is there any way to use in the templateProvider the information previously fetched in the resolve avoiding this way another call to database?
Right now, it is doing 2 calls to database per connection...
Thanks!
app.factory('article', function ($cacheFactory){
var articleCache = $cacheFactory('article');
return function (url) {
return articleCache.get(url) || articleCache.put(url, $http({
method: 'GET',
url: '/articles/' + url
})
);
};
});
Use it as article($stateParams.articleUrl).then(...) in both places, that will keep the things DRY. You may get better control over the cache (e.g. expiration) by replacing $cacheFactory with angular-cache.
$http own caching may be successfully used as well instead of explicit caching:
If there are multiple GET requests for the same URL that should be
cached using the same cache, but the cache is not populated yet, only
one request to the server will be made and the remaining requests will
be fulfilled using the response from the first request.
I think you can inject directly the resolved variables, so you could inject article in templateProvider:
.state('articleurl', {
url: '/:articleUrl',
resolve: {
article: function ($http, $stateParams, $location) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
})
.then(function (article) {
return article;
}, function (error) {
$location.path('/404');
});
},
loggedin: checkLoggedin
},
templateProvider: ['$templateFactory', '$stateParams', '$http', 'article', function ($templateFactory, $stateParams, $http, article) {
// Now here you can use article without the need to re-call it
}],
controller: 'ArticlesViewController'
})

angularjs getting data from a url

I want to get json data from the url and assign it to a variable. I use a service that looks like this
app.service('dataService', function($http) {
this.getdata = function(callbackFunc) {
$http({
method: 'GET',
url: '/records/json/',
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
and my controller looks like this
app.controller('ReCtrl', ['$scope', function($scope, dataService){
dataService.getdata(function(dataResponse) {
$scope.fields = dataResponse;
});
....
But I get error TypeError: Cannot read property 'getdata' of undefined. I dont know what i am doing wrong. I appreciate any help.
You are not injecting your service (dataService) into your controller:
app.controller('ReCtrl',
['$scope', 'dataService', function($scope, dataService){
dataService.getdata(function(dataResponse) {
$scope.fields = dataResponse;
});
....
Note the extra string 'dataService' after '$scope' while defining the controller ReCtrl.

returning value to higher scope inside from a chained functions in angular js

I have a function getUsers that I want to return JSON from an web api .. but I cant seem to get the data out, I can't return the data because the function is inside $http. What should i do ?
function getUsers() {
$http({ method: 'GET', url: '/api/loginapi/userdetails' })
.success(function (data, status, headers, config) {
details = data;
});
return details;
}
$http makes an asynchronous call, so you can't immediately return fetched data.
What you can return is a promise. Good news, $http() returns one:
function getUsers() {
return $http({ method: 'GET', url: '/api/loginapi/userdetails' });
}
Then you can use your function:
getUsers().then(function(data) {
var details = data;
// Process your details!
});
You can access data there for sure, nothing is 'inside' $http, I suggest you pass in a callback to getUsers() and do whatever you want with the returned data:
var getUsers=function(callback){
$http({ method: 'GET', url: '/api/loginapi/userdetails' })
.success(function (data, status, headers, config) {
callback(data);
});
}
and use it like this inside your controller:
getUsers(function(users){
$scope.whatever = users;
})
I created plunkr for your question http://plnkr.co/edit/lqX4apmvnKM3i5jGZDQM?p=preview
$http return a promise. Please read details about promise at http://johnmunsch.com/2013/07/17/angularjs-services-and-promises/ . It is an important understanding if you want to write asynchronous application. This is another useful link - Inside my own Angular service, how do you get the return value back to the Controller that called the service? . Refer to answer. It explains how to use promise and deffered in angularjs.
var app = angular.module('plunker', []);
app.service('UserService', ['$http', '$q',
function($http, $q) {
this.getUser = function() {
return $http({
method: 'GET',
url: 'data.json'
});
};
}
]);
app.controller('MainCtrl', function($scope, UserService) {
$scope.user = {};
UserService.getUser().then(function(response){
$scope.user = response.data;
});
});

AngularJS: Call a particular function before any partial page controllers

I want to call a particular function: GetSession() at the beginning of my application load. This function makes a $http call and get a session token: GlobalSessionToken from the server. This session token is then used in other controllers logic and fetch data from the server. I have call this GetSession()in main controller: MasterController in $routeChangeStart event but as its an asynchronous call, my code moves ahead to CustomerController before the $http response.
Here is my code:
var GlobalSessionToken = ''; //will get from server later
//Define an angular module for our app
var myApp = angular.module('myApp', ['ngRoute']);
//Define Routing for app
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/customer', {
templateUrl: 'partials/customer.html',
controller: 'CustomerController',
resolve: {
loadData: function($q){
return LoadData2($q,'home');
}
}
}).
otherwise({
redirectTo: '/home'
});
}]);
//controllers start here and are defined in their each JS file
var controllers = {};
//only master controller is defined in app.js, rest are in separate js files
controllers.MasterController = function($rootScope, $http){
$rootScope.$on('$routeChangeStart', function(){
if(GlobalSessionToken == ''){
GetSession();
}
console.log('START');
$rootScope.loadingView = true;
});
$rootScope.$on('$routeChangeError', function(){
console.log('ERROR');
$rootScope.loadingView = false;
});
};
controllers.CustomerController = function ($scope) {
if(GlobalSessionToken != ''){
//do something
}
}
//adding the controllers to myApp angularjs app
myApp.controller(controllers);
//controllers end here
function GetSession(){
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
}).error(function (data, status, headers, config) {
console.log(data);
});
}
And my HTML has following sections:
<body ng-app="myApp" ng-controller="MasterController">
<!--Placeholder for views-->
<div ng-view="">
</div>
</body>
How can I make sure this GetSession() is always called at the very beginning of my application start and before any other controller calls and also called only once.
EDIT: This is how I added run method as per Maxim's answer. Still need to figure out a way to wait till $http call returns before going ahead with controllers.
//Some initializing code before Angular invokes controllers
myApp.run(['$rootScope','$http', '$q', function($rootScope, $http, $q) {
return GetSession($http, $q);
}]);
function GetSession($http, $q){
var defer = $q.defer();
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
defer.resolve('done');
}).error(function (data, status, headers, config) {
console.log(data);
defer.reject();
});
return defer.promise;
}
Even though some of the solutions here are perfectly valid, resolve property of the routes definition is the way to go, in my opinion. Writing your app logic inside session.then in every controller is a bit too much , we're used such approach too in one of the projects and I didn't work so well.
The most effective way is to delay controller's instantiation with resolve, as it's a built-in solution. The only problem is that you have to add resolve property with similar code for every route definition, which leads to code duplication.
To solve this problem, you can modify your route definition objects in a helper function like this:
function withSession(routeConfig) {
routeConfig.resolve = routeConfig.resolve || {};
routeConfig.resolve.session = ['getSessionPromise', function(getSessionPromise) {
return getSessionPromise();
}]
return routeConfig;
}
And then, where define your routes like this:
$routeProvider.when('/example', withSession({
templateUrl: 'views/example.html',
controller: 'ExampleCtrl'
}));
This is one of the many solutions I've tried and liked the most since it's clean and DRY.
You can't postpone the initialisation of controllers.
You may put your controller code inside a Session promise callback:
myApp.factory( 'session', function GetSession($http, $q){
var defer = $q.defer();
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
defer.resolve('done');
}).error(function (data, status, headers, config) {
console.log(data);
defer.reject();
});
return defer.promise;
} );
myApp.controller( 'ctrl', function($scope,session) {
session.then( function() {
//$scope.whatever ...
} );
} );
Alternative: If you don't want to use such callbacks, you could have your session request synchronous, but that would be a terrible thing to do.
You have not provided any details related to GetSession. For scenarios like this you should use the resolve property while defining your routes in $routeProvider. I see you are using resolve already.
What you can do now is to wrap the GlobalSessionToken into a Angular service like GlobalSessionTokenServiceand call it in the resolve to get the token before the route loads. Like
resolve: {
loadData: function($q){
return LoadData2($q,'home');
},
GlobalSessionToken: function(GlobalSessionTokenService) {
return GlobalSessionTokenService.getToken() //This should return promise
}
}
This can then be injected in your controller with
controllers.MasterController = function($rootScope, $http,GlobalSessionToken){

Categories

Resources