Inside my controller I have a call to fetch a document from my back end that looks like this:
orderFactory.query({_id: $stateParams.obj}).$promise.then(
function (response) {
console.log(response);
$scope.invoice = response[0].invoice;
$scope.client = response[0].client;
$scope.orderdetails = response[0].orderdetails;
},
function (response) {
console.log(response);
$scope.message = "Error: " + response.status + " " + response.statusText;
});
But the problem is that this code sends a GET request to /orders&_id=5926bef0f5344c1ff8a9b295 but the REST end point it should access is /orders/5926bef0f5344c1ff8a9b295
The URL in the browser is /trackdetails and I cant use $stateParams to access the end point desired
So my question is there any way to access that end point from the controller? Or perhaps I have to rework my architecture?
In resource:
$resource('your_url/:_id',
{
_id: '#_id'
}
)
In component:
orderFactory.get({_id: $stateParams.obj}, function(response) {
// success
}, function(reject) {
// error
})
Related
I am new to angular-js and building a simple to-do application. I am creating a task and displaying the created task in a html table using ng-repeat. But the problem is that after posting the data, $scope.tasks variable is updated on controller side, but not in view. The view updates after refreshing the web page only and the task is added to html table. How can I make the view update after creating the task. Thanks in advance. Here is my code:
In my controller:
var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);
app.controller('DemoCtrl', function($scope,$mdSidenav,$mdDialog,$interval,$http,$mdToast) {
$scope.tasks = [];
_refreshTaskData(); //initial refresh
$scope.submitForm = function() {
var description = "";
var taskId = "";
$scope.formData = {
taskId: $scope.taskId,
description: $scope.description,
};
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(_success, _error);
};
function _refreshTaskData() {
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(res) { // error
console.log("Error: " + res.status + " : " + res.data);
});
}
function _success(res) {
$mdDialog.hide();
console.log('in success function');
_refreshTaskData(); ;
}
function _error(res) {
//error handling
}
});
In my view:
<table>
<tr ng-repeat=" t in tasks">
<td>{{t.id}}</td>
<td>{{t.description}}</td>
</tr>
</table>
You must understand that these JS frameworks are asynchronous. Now what happens is, if you do an API call and make another API call whose result is based on the first one, the console does not wait for the result from one API and directly moves forward. SO what's happening in your case is sometimes/many times, before the POST call is served, the controller is not able to get fresh data with GET in time, thus not updating the view. What you can possibly do is enforce the GET only when POST is served
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(function(res){
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(err) { // error
console.log("Error: " + err.status + " : " + err.data);
});
});
It would be best if you are sending a success message from the backend and checking before GET call
I think you are not calling _refreshEmployeeData at any point of time. If you add that instead of _refreshTaskData in your JS, then you will be able to see the result in view.
Also kindly use ng-init to call the _refreshEmployeeData in the controller. That would be the best way to initialize the fields.
When i tried to access star wars API using $http method . am getting 403 response with message "Invalid basic header. No credentials provided" what am missing here?
$http({
method : 'GET',
url : 'https://swapi.co/api/people/'
}).then(function(success) {
var data = JSON.parse(body);
var result = data.result.filter(function each(r) {
return username == r.name && password == r.birth_year;
});
}, function(error) {
alert('not logged::' + eror)
});
Could you please someone help me to find the issue?
You are using wrongly the data returned by the get call.
You don't need to parse it to JSON, it's already a JSON.
Here's a plunker with a call to the API working. Hope it helps you
https://plnkr.co/edit/WKQfqc7wxmBJIjYUyZKe
angular.module('myApp', []).controller('myAppController', function($http, $scope) {
$scope.callApi = function() {
$http.get('https://swapi.co/api/people/').then(function(result) {
$scope.characters = result.data.results;
}, function(error) {
alert('not logged::' + error)
});
}
});
I am new to angularJS. I am using ionic framework for android application development. In my project I am calling webservice and getting its response and attaching that response to scope variable to get data on the view. First time webservice called and updates the view as expected but when I call the service again that is not updating my data. It seems as ng-repeat is not working due to some reference loosing problem. But I am not able to find out the solution of that. Although I have tried different solution via using apply() as was mentioned in one of the stack overflow posts. Below is the code of attaching web-service response to the scope variable.
$http(req).then(function (response) {
if (response.data.IsSuccess) {
console.log("data = " + JSON.stringify(response.data));
console.log('Response is '+response.data.IsSuccess);
$scope.companies = response.data.Response.Companies;
}
and below is the line of code using to update the view
<div class="col col-100" ng-repeat="company in companies">
any help or advice
Below is the login code that is calling webservice to update my data
function callLogInService(userName, password){
console.log("user name is " +userName);
console.log("password is " + password);
var req = {
method: 'POST',
url: ApiUrl + '/api/User/LoginUser',
headers: {
'Content-Type': 'application/json'
},
data: {
Email: userName,
Password: password
}
}
$ionicLoading.show({
template: 'Signing in...'
});
$http(req).then(function (response) {
if (response.data.IsSuccess) {
console.log("data = " + JSON.stringify(response.data));
console.log('Response is '+response.data.IsSuccess);
var userID = response.data.Response.AppUserId;
var userName = response.data.Response.AppUserName;
setUserName(userName);
setUserId(userID);
$rootScope.appUserName;
var userIdFromSession = getUserID;
if(undefined == $rootScope.companyIdForSubscription
|| $rootScope.companyIdForSubscription == 0){
console.log("id is undefined for subscription");
} else {
console.log("company subscription id is " + $rootScope.companyIdForSubscription);
$scope.subscribe($rootScope.companyIdForSubscription);
}
$scope.close();
$scope.setVisibilityOdSideMenuIcons();
$scope.getAllCompanies();
}
else {
showErrorAlertDialogue(response.data.ErrorMessage);
}
}, function (reason) {
console.log('reason is ' + reason.data);
$log.info('reasonf log is' + reason) ;
showErrorAlertDialogue("Please check your internet connection.");
}).finally(function () {
console.log("finally is called");
$ionicLoading.hide();
$ionicPopup.close()
});
}
$scope.getAllCompanies(); this line is calling service again
I am writing an angular service which I will use to get and manipulate data from SharePoint lists/libraries. I am trying to use best practices for $http promises but I am having trouble finding the best way to accomplish what I want. Here is one of my functions in my service:
this.GetListItemById = function (webUrl, listName, itemId, loading) {
var url = webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")";
return $http({
url: url,
method: 'GET',
processData: false,
headers: { "Accept": "application/json;odata=verbose" },
}).then(function SuccessCB(response) {
return response.data.d;
}).catch( function FailureCB(response) {
throw response;
});
};
And then here is where I use it in my controller:
$scope.GetListItemById = function (webUrl, listName, itemId) {
SPListUtility.GetListItemById(webUrl, listName, itemId)
.then(function success(data) {
console.log(JSON.stringify(data));
$scope.animateAlert("myAlert", "alertText", "Item: " + data.Title + " loaded", "success");
}).catch( function failure(error) {
console.log("Error " + error.status + ": " + error.statusText);
$scope.animateAlert("myAlert", "alertText", "Error " + error.status + ": " + error.statusText, "danger");
});
};
This is working as intended, it returns the item data if it is found on the server and if it is not then the 404 bubbles up to my controller and my error alert is called and logged to the console. My problem with this though is it keeps bubble up and angular catch statements are tripped which causes the following in the log: Console log image
Is there a way to stop angular from blowing out the log? Also am I following best practices here? If not what should I change?
When you throw inside a catch block it doesn't just reject the promise. It also triggers angular's exception handler which by default will log the exception (you can replace the default implementation of this if you want). If you wanted to reject a promise from a reject block without triggering the exception handler you could return a rejected promise. e.g.
return $q.reject(response);
That being said your catch block that is throwing the response isn't necessary. The exact same behavior will occur if you just remove it (except for the logging)
i'm working on a project like this:
(HTML Forms(AJAX)+ twitter bootstrap)(solo HTML, no JSP,etc..)->Servlets(on Google App Engine-JAVA)->Persistence(Google Cloud SQL).
I'm quite new to jQuery ajax calls, but i understand the process, as i'm used to write the old XHR code.
Below is the function in JS, that does not write to console the expected result..so far most of the times form data is persisted.
My Servlet if fine, and outputs a valid JSON.(calling the URL on a browser always works as expected.)
My answer is why jQuery ajax callbacks(done,fail,always) aren't working properly? They do write to console/display alert().
THANKS, for your time!
$(document).ready(function() {
var myEmail = "";
var myGender = "";
$('#saveButton').click(function() {
$('#myform').submit();
//alert('Handler for .submit() called.');
myEmail = document.getElementById("inputEmail").value;
window.console.log('EMAIL---->' + myEmail);/*ok log!*/
//alert('EMAIL->' + myEmail);
var radioObj = document.forms['myForm'].elements['gender'];
myGender = getCheckedValue(radioObj);
window.console.log('GENDER---->' + myGender);/*ok log!*/
//alert('GENDER->' + myGender);
var jqXHR = $.ajax({
statusCode : {
404 : function() {
alert("404 ERROR - page not found");
}
},
url : "/newuser",
type : "GET",
timeout : 10000,
data : {
email : myEmail,
gender : myGender,
operation : '0'
},
done : function(data, textStatus, jqXHR) {
window.console.log('done -> RESPONSE---->' + data);/*this does not log!*/
alert(data);
},
fail : function(jqXHR, textStatus, errorThrown) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
},
always : function(data, textStatus, jqXHR) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
}
});
});
});
done, fail and always are not properties of the settings object passed to $.ajax, they are callbacks on the jqxhr object returned by the call to $.ajax. They should be configured like this instead:
var jqxhr = $.ajax( "example.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
Check out the API documentation for further usage guidance.