var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("myservice").then(function (response) {
$scope.studentdata = response.data;
});
});
Based on student data i need to call other service like student address.how to achieve i am new to angular js please help.
You need to use promise chains to call the request after another
function firstReq(){
return $http({
method: 'POST',
url: 'http://localhost/api/users',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify($scope.user)
})
}
function secondReq(){
return $http({
method: 'POST',
url : 'http://localhost/api/users/' +$scope.user_id + '/accessTokens',
})
}
$scope.processform = function() {
firstReq()
.then( function( response )
{
console.log(response.data.user_id);
$scope.user_id = response.data.user_id;
return secondReq();
})
.then(function(response){
console.log(response.data);
})
}
Related
firstapp
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
sencond app
var app = angular.module('myApp2', []);
app.controller('myCtrl2', function($scope, $http) {
$http.get("fsd.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
How to Pass data from one app to another app in angularjs ?
You can use shared service to communicate between two angular apps.
However using multiple apps is not a good practice unless it is the only option left.
angular.module('sharedService', []).factory('SharedService', function() {
var SharedService;
SharedService = (function() {
function SharedService() {}
SharedService.prototype.setData = function(name, data) {};
return SharedService;
})();
if (typeof(window.angularSS) === 'undefined' || window.angularSS === null) {
window.angularSS = new SharedService();
}
return window.angularSS;});
angular.module("angularApp1", ['sharedService'])
/*code */
angular.module("angularApp2", ['sharedService'])
/*code */
Create function like this in Service Lyaer
editTool: function(yourData) {
var basicAuth = YOurauthenticateFuntion;
var url = 'url';
var deferred = $q.defer();
$http.post(url, yourData, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': basicAuth
}
}).then(function(data) {
if(data.status == 200) {
deferred.resolve(data.data);
} else {
deferred.reject(data);
}
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
and then can call in any controller using factory name.. that you have created for serviceCalls
I'm trying to pass data back to my controller from my service with no success. I am able to invoke my service from my controller, and I know the service itself works because I can console log the response from within the service (but not back in the controller).
This is my service:
(function () {
angular
.module('app')
.service('testService', testService);
testService.$inject = ['$http'];
function testService($http, url) {
var baseUrl = "http://getjsondata.com/" + url;
this.getData = function (url) {
$http({
method: 'GET',
url: baseUrl + url,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
console.log(response); // THIS WORKS
return response;
})
.catch(function (error) {
return error;
});
};
}
}());
This is inside my controller:
vm.getTestData = function (url) {
vm.response = testService.getData(url);
console.log(vm.response);
};
I've tried passing the data back as a callback in testService.getData but with no success. I have also tried using a factory instead of a service but I'm not able to access the data back in my controller. I have also tried defining my function in the service differently (getData: function()...) and so on.
I'm guessing my return statement in the service is behaving differently than the way I am expecting. I would appreciate any help!
getData never returns. add return in front of $http and use .then in your controller.
this.getData = function (url) {
return $http({
method: 'GET',
url: baseUrl + url,
headers: {'Content-Type': 'application/json'}
})
};
In ctrl
vm.getTestData = function (url) {
testService.getData(url).then(function (response) {
vm.response = response;
return response;
})
.catch(function (error) {
return error;
});
};
I am new on angular JS. I am tried to implement $http in the response of $http.
My issue is that when i call $http in response of anoter $http. It doesn't show the data on view. The view is rendered before the second $http call. I have used promises but no luck. Here is the code from other answer which i used by changing a little.
angular.module('App', [])
.controller('Ctrl', function($scope, resultsFactory) {
resultsFactory.all().then(
function(res){
$scope.results = res;
},
function(err){
console.error(err);
}
);
})
.factory('resultsFactory', function($http, $timeout, $q) {
var results = {};
function _all(){
var d = $q.defer();
$http({
url: url,
method: 'POST'
}).then(function (response) {
var f = {};
f.id = response.data.id;
f.name = response.data.name;
$http({
url: url,
data: "id="+response.data.parent_id,
method: 'POST'
}).then(function (response1) {
f.parentname = response1.name;
d.resolve(f);
});
});
return d.promise;
}
results.all = _all;
return results;
});
The id and name is shown properly on view but it is showing nothing for parent name. I have debug it. It is undefined when rendering view. After rendering it is setting their value to parentname. Can any one help me to resolve this issue?
You shouldn't need a deferred for this: just chain the promises:
return $http({
url: url,
method: 'POST'
}).then(function (response) {
var data = {};
data.id = response.data.id;
data.name = response.data.name;
return $http({
url: url,
data: "id="+response.data.parent_id,
method: 'POST'
}).then(function (response1) {
data.parentname = response1.name;
return data;
});
});
You overwrote your d variable...
.factory('resultsFactory', function ($http, $timeout, $q) {
var results = {};
function _all() {
var d = $q.defer();
$http({
url : url,
method : 'POST'
}).then(function (response) {
var secondD = {};
secondD.id = response.data.id;
secondD.name = response.data.name;
$http({
url : url,
data : "id=" + response.data.parent_id,
method : 'POST'
}).then(function (response1) {
secondD.parentname = response1.name;
secondD.resolve(d);
});
});
return d.promise;
}
results.all = _all;
return results;
});
I am using AngularJs and backend CodeIgniter REST API .Here is the sample of code
data.js
`
app.factory("Data", ['$http', 'toaster','$log',
function ($http, toaster,$log) {
// This service connects to our REST API
var serviceBase = 'link';
var obj = {};
obj.toast = function (data) {
toaster.pop(data.status, "", data.message, 10000, 'trustedHtml');
}
obj.get = function (q) {
return $http.get(serviceBase + q).then(function (results) {
return results.data;
});
};
obj.post = function (q, object) {
//$log.log(object.customer);
$http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "key"
},
data: object.customer
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
obj.put = function (q, object) {
return $http.put(serviceBase + q, object).then(function (results) {
return results.data;
});
};
obj.delete = function (q) {
return $http.delete(serviceBase + q).then(function (results) {
return results.data;
});
};
return obj;
}]);
authctrl.js
app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data,sData) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.signup = {};
$scope.doLogin = function (customer) {
Data.post('login', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.signup = {email:'',password:'',name:'',phone:'',address:''};
$scope.signUp = function (customer) {
sData.post('signUp', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.logout = function () {
Data.get('logout').then(function (results) {
Data.toast(results);
$location.path('login');
});
}
});
It is having an error which is
TypeError: Cannot read property 'then' of undefined
at h.$scope.doLogin (authCtrl.js:8)
at $a.functionCall (angular.min.js:172)
at angular.min.js:189
at h.a.$get.h.$eval (angular.min.js:108)
at h.a.$get.h.$apply (angular.min.js:109)
at HTMLButtonElement. (angular.min.js:189)
at angular.min.js:31
at q (angular.min.js:7)
at HTMLButtonElement.c (angular.min.js:31)
And also as you can see i am using single post method for both login and signUp function .So what i want to make it separate function like
For Login
obj.post = function (q, object) {
//$log.log(object.customer);
$http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "3e9aba65f0701f5e7c1c8a0c7315039e"
},
data: object.customer
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
For Sign up
obj.post = function (q, object) {
//$log.log(object.customer);
$http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "3e9aba65f0701f5e7c1c8a0c7315039e"
},
data: object.customer
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
How to write it in angularJs?
because you are returning nothing from Data.post, instead of returning the promise .
i.e. change your Data.post to
obj.post = function (q, object) {
//$log.log(object.customer);
return $http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "key"
},
data: object.customer
});
};
I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User.
When i debug the code i found that it call success first and then it goes for Ajax call.
When i do ajax call without service it works fine.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
this.SearchEmployee = function () {
// Ajax call
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.userUsers = response.data;
this.errors = '';
};
var onError = function (reason) {
this.userUsers = reason;
this.errors = "Error in retrieving data.";
};
return this.Users;
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.Id = '';
this.name = '';
this.expertise = '';
$scope.repoSortOrder = 'id';
$scope.filterField = '';
// Call to service
this.GetAllEmployee = function () {
// Initiates the AJAX call
$scope.User = EmployeeSer.SearchEmployee();
// Returns the promise - Contains result once request completes
return true;
};
this.AddEmployee = function () {
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
$http({
method: 'POST',
url: '/Home/Create',
params: JSON.stringify(empData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
// Returns the promise - Contains result once request completes
return true;
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
It's because you are returning the users before the data is fetched from the server. Also it doesn't seem like you are assigning them correctly.
Here are two ways to solve the problem:
Firstly. You bind your controller user-data to the user-data in the service.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.Users = response.data;
this.errors = '';
};
var onError = function (reason) {
this.users = null;
this.errors = "Error in retrieving data.";
};
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.users = EmployeeSer.users;
EmployeeSer.SearchEmployee();
}]);
And the second way would be to return the promise in the service and unwrap it in the controller.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.SearchEmployee = function () {
return $http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.GetAllEmployee = function () {
EmployeeSer.SearchEmployee()
.then(onSuccess, onError)
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
OFF TOPIC
You should probably consider using ngModel instead of jQuery to get you data to the controller.
Not like this:
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
// Here serverRequest is my service to make requests to the server
serverRequest.postReq = function(url, data, sucessCallback, errorCallback){
$http({
method: 'POST',
url: urlToBeUsed,
data:data,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, headers, config) {
sucessCallback(data);
})
.error(function(data, status, headers, config){
errorCallback(data);
})
}
// In the controller
serverRequest.postReq('urlToBeCalled', dataToBeSent, scope.successCb, scope.errorCb);
scope.successCb = function(data){
// functionality to be done
}
scope.errorCb = function(data){
// functionality to be done
}
Try it this way your problem might be solved
Promise must be unwrapped in your controller if you want to use it