How to get id from $http.get in angular.js - javascript

Hi I am a newbie and learning angular.js. I want to get data from this url which is actually an API (http://ba.dev/businesses/businesspage/36) but i dont know how can i Write this thing in my controller.js file. Given is my code please explain me how can I get the data from the business having id=36.
var reControllers = angular.module('reControllers',[]);
reControllers.controller('RecentController', ['$scope','$http' ,function($scope,$http){
$http.get('http://ba.dev/businesses/businesses').success(function(data){
$scope.business = data;
});
}]);
reControllers.controller('PageController', ['$scope','$http', '$routeParams' ,function($scope,$http,$routeParams){
$http.get('http://ba.dev/businesses/businesspage').success(function(data){
$scope.student = data;
$scope.whichItem = $routeParams.itemId;
});
}]);
Here is my app.js file
var myApp = angular.module('myApp',[
'ngRoute',
'reControllers'
]);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main',{
templateUrl : 'partials/main.html',
controller : 'RecentController'
}).
when('/page/:itemId',{
templateUrl : 'partials/page.html',
controller : 'PageController'
}).
otherwise({
redirectTo: '/main'
});
}]);

You can get the id from URL using $routeParams
$http.get('http://ba.dev/businesses/businesspage/'+ $routeParams.itemId)
Thereafter add server side logic, get passed itemId from URL, perform needful operation for getting data from DB and return it back.

You should use then instead of success, because it is deprecated. So, your code should be: `
$http.get('http://ba.dev/businesses/businesses').then(function(data){
$scope.business = data;
}); }]);.....
From AngularJS documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
More info about route params: AngularJS $routeParams

Related

Angular not displaying $scope data with ng repeat passed in controller. No errors too

In this project, I am executing a query on click list item of ionic. I am getting the data from php json_encode. The data is getting displayed in the networks tab under response. Also, I have added $scope.doctorList = {}; and after that wrote this line $scope.doctorList = response which comes from success function. The data is getting displayed in console.log($scope.doctorList) as well.
Now when I try to display this data in angular, it does not show anything.
I have included it in ng-repeat as : ng-repeat = "doctors in doctorList"
The syntax seems to be correct as the same thing is working for another controller but here, I can't retrieve the data. The page goes blank and there is no error in console / netowrks tab.
I am using one controller for two html files. Please help
Here is the routes file
angular.module('app.routes', []).config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider.state('homeselect', {
url: '/home-select',
templateUrl: 'templates/homeselect.html',
controller: 'homeCtrl'
});
$stateProvider.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
});
});
Here is the controller
angular.module('app.controllers', []).controller('homeCtrl', function ($scope, $http, $ionicSideMenuDelegate, myServices, $window) {
$ionicSideMenuDelegate.toggleLeft();
$scope.loadDoc = function (type) {
$http({
url: "http://localhost/drmedic/retrieve_details_type.php",
method: "POST",
data: {
data: type
}
}).success(function (response) {
$scope.doctorList = {};
$scope.doctorList = response;
$window.location.href = '#/home-select';
});
};
$http({method: 'GET', url: 'http://localhost/drmedic/retrieve_details.php'}).success(function (data) {
$scope.contents = {};
$scope.contents = data;
});
});
Here is the html file code for ng-repeat
<ion-list ng-repeat="doctors in doctorList">
<ion-item>
<center>
{{doctors.name}}<br>
{{doctors.fees}}
</center>
</ion-item>
</ion-list>
You can use service.Open a file called service.js.After that this inject to app.js. I revised the code as follows:
Service.js:
angular.module('app.services', [])
.factory("AppService", function ($http) {
var AppService= {};
AppService.GetDetails = function (data) {
return $http({
url: "http://localhost/drmedic/retrieve_details_type.php",
method: "POST",
data: {
data: data
}
});
return AppService;
}
controller.js:
.controller('homeCtrl',function($scope,$http,$ionicSideMenuDelegate,myServices,$window,AppService) {
$ionicSideMenuDelegate.toggleLeft();
$scope.loadDoc = function(type){
AppService.GetDetails({type:type}).success(function (response) {
$scope.doctorList = {};
$scope.doctorList = response;
$window.location.href = '#/home-select';
})
.error(function (err) {
console.log(err);
});
}
});
ng-repeat iterates through a collection of items, create its own scope and renders it on UI. When I say collections, it should be an array.
https://docs.angularjs.org/api/ng/directive/ngRepeat
Please check the data-type for doctorList, which I believe is an array.
$scope.doctorList = [];
I hope this should solve the problem, if not please share the code I'll take a deep look into it.

RouteParams in AngularJS

I am trying to pass a routeParam to a $http.post in my Angular controller, but I dont seem to be passing the value correctly. Here is what I have below. Am an not using the $routeParams correctly? When using $scope.event_id = $routeParams.eventId; the partial page renders correctly with Event: {{event_id}} or Event: 5 for example.
I need the $http.post to be php/getItem.php?itemID=5
The HTML passing the event_id:
{{event.event_name}}
The routeProvider:
var pvApp = angular.module('pvApp', ['ngRoute']);
// configure our routes
pvApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventController'
});
});
The Controller:
pvApp.controller('eventController', function($scope, $http, $routeParams) {
// $scope.event_id = $routeParams.eventId;
$http.post("php/getItem.php?itemID="+$routeParams.eventId).success(function(data){
$scope.items = data;
});
});
The Partial Page:
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Event: {{event_id}}</h2>
</div>
</div>
</div>
first check
console.log($routeParams.eventId);
is print the event_id on the console correctly.
Then
Note that your using a POST request but your url like GET request.
change the request like below and try,
$http({
url: 'php/getItem.php',
method: "POST",
data: { itemID : $routeParams.eventId },
}).succes...
OR
$http.post('php/getItem.php', { itemID:$routeParams.eventId }).success...
here you can get the data in Php as,
$data = json_decode(file_get_contents("php://input"));
$data->itemID // to access name
OR
$http({
url: 'php/getItem.php',
method: "POST",
data: { itemID : $routeParams.eventId },
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).succes...
In Php,
$name= $_POST['itemID'];
may be this post will helps you.

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.

How to get json data in my case?

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);
}
});

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