My angularJs function returns response in Json, but I am not been able to get the 'model' part out from it.
Below is my code:
this.search = function () {
var response = $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
return response;
}
this.search().then(function (response) {
console.log('conscole: ' + response.data.model)
})
this.search().then(function (response) {
console.log(response.data.model)
})
And below is my mvc method:`
List<CandidateSearchViewModel> output = CRBuilderObj.ContructResultsViewModel(data);
CandidateSearch.model = output;
CandidateSearch.baseCriteria = criteria;
return Ok(CandidateSearch);
if you want to access the response of the http request then you have to resolve the promise firs. then access the model property from the response
this.search = function () {
return $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
}
//resolve the promise like this
this.search().then(function(response){
console.log(response.data.model)
})
Related
I need to create service in AngularJS to return the response of HTTP requests. My problem is the asynchronous request, because after I've submitted the request, my function returns undefined instantly and does not return the response from the server.
app.service('TesteService', function($http) {
this.teste = function(data) {
var data = "*";
$http({
method: 'GET',
url: 'teste-s.php',
params: {data: "bem recebido"}
}).then(function successCallback(response) {
data = response.data;
alert(data);
return data;
}, function errorCallback(response) {
data = "500";
});
}
});
How do I fix this?
I want to submit data from a form and display the result in the view directly after http request returns a result. But it's not happening.
$scope.formData = {};
$scope.add = function (){
$http.post('add.php',$scope.formData,{'Content-Type': 'application/x-www-form-urlencoded'})
.then(function (result) {
console.log(result.data);
if (result){
$scope.data = result.data;
}
});
};
And this is add.php. In this file I just want to return the posted data in json.
function index(){
$data = $this->input->post();
echo json_encode($data);
}
I find it returns false value. I wonder how I process data submitted with post method using $http.post like this.
You can try this way to pass data to add.php service
$scope.add = function (){
$http({
method: 'POST',
url: 'add.php',
headers: {
'Content-Type': application/x-www-form-urlencoded
},
data:$scope.formData
}).then(function successCallback(response) {
$scope.data = response.data.data;
}, function errorCallback(response) {
console.log(response);
});
}
Try this in PHP:
$data = $this->input->post(NULL, TRUE);
In AngularJS, inject $httpParamSerializerJQLike in your service/factory
$scope.add = function (){
$http({
method: 'POST',
url: '/add.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializerJQLike($scope.formData);
}).then(function resolve(response) {
console.log(response);
$scope.data = response.data.data;
}, function reject(response) {
console.log(response);
});
}
I am trying to pass an http response from my controller to a service, it works well except for getting the response to go into the controller here is my code below:
For my service
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload,callBack){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function successCallback(callBack){
console.log(callBack);
return deferred.resolve(callBack);
}, function errorCallback(callBack){
//deferred.reject(error);
console.log(callBack);
return deferred.reject(callBack);
});
return deferred.promise;
}
}
});
and for the Controller
app.controller('LoginCtrl', function($scope,$position,$rootScope,$state,ApiService) {
$scope.forms = {
'loginForm':''
}
var payload ={
'username':'',
'password':''
}
$scope.userLogin = function(form){
$scope.username = form.username.$modelValue;
$scope.password = form.password.$modelValue;
payload ={
"username":$scope.username,
"password":$scope.password
}
ApiService.login(payload, function(result){
console.log(result);
}
});
Now I don't understand because when I console.log() the response I'm able to see it in the service but doing the same on the controller I'm getting nothing.
No need to make it complex. Simply return promise from factory and use it in controller.
factory:
app.factory('ApiService',function($http,Config,$q) {
return {
login: function(payload) {
return $http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
});
}
}
});
in controller :
ApiService.login(payload).then(function(data){
// use response data
}, function(error) {
// handle error
});
You should use it like this:
ApiService.login(payload).then(function(result){
console.log(result);
});
Because you are returning a promise in your service.
Also you don't need that callback parameter, because the then method on the promise is your callback when it finishes and you can access the data your resolve it with.
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function (result){
return deferred.resolve(result);
}, function (result){
return deferred.reject(result);
});
return deferred.promise;
}
}
});
Am trying to hit web service with a directive controller, I hit the post method and got the response, but values I expected are become empty because all compiled before the success response.
This is my controller within the directive
controller: ['$scope', '$http', 'popupService','SessionUtils', function($scope, $http, popupService,SessionUtils) {
$scope.responseValue = "";
$scope.sendCSVFile = function(link, fileData) {
$scope.seriveResponse = $http({
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
and I called the controller from the directive link function like
var res = scope.sendCSVFile(attrs.getUrlModel, formData);
scope.gridUpdate(res);
the value res returning undefined, but I get the response after I binded the res. How to I get the promising response and execute the function after.!
You can get promise, not standard data, ajax is asynchronous call, so change code to:
$scope.sendCSVFile = function(link, fileData) {
return $http({ //return promise object
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
usage:
$scope.sendCSVFile(attrs.getUrlModel, formData).then(function(response){
//here ajax is completed and in response variable You have raturn from success callback
if (response)
scope.gridUpdate(response);
});
i' using AngularJS v1.4.2. i have 2 html page , they have 2 controller.both controller have save event. how to use use http post method
first controller i'm calling post method given below
var promisePost = crudService.post(Countries);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getCountry();
$stateParams.country = "";
}, function (err) {
alert("NOt Inserted")
});
second controller i'm calling post method given below
var promisePost = crudService.post(Levels);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getLevel();
}, function (err) {
alert("NOt Inserted")
});
my app.js
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.post = function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.post = function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
but this code only take last post method.How to selecet post method properly. Anyone can helpme?
User countryPost and levelPost as follows and call those accordingly.
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.countryPost= function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.levelPost= function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
The best practice for using services is to return an object from it
myapp.factory('crudService', function ($http, RESOURCES) {
return {
saveCountry : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
},
saveLevel : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
}
}
});
then inject it into your controller dependencies and use it like :
crudService.saveLevel().then(function(){
//do some code here
})
Create a single post method instead and receive the url to call in it as parameter along with the data. As shown below:
this.post = function (data, remainingUrl) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + remainingUrl,
data: data
});
return request;
}