I try to make an application with PhoneGap and AngularJS that can be used online and offline (for Android device).
I want to get a list of people from the local database if the device is offline, and from a web service, using $http, if the device is online. But when the device is online, it doesn't work, web service isn't called.
I think the problem is PhoneGap asynchronous method. Indeed, in offline mode, it works but i need to use $scope.$apply to update my view. But that doesn't work for $http...
Does someone know how to use $http in asynchronous method?
function ListCtrl ($scope, $http){
$scope.list = [];
$scope.Id = 2;
$scope.init = function(){
document.addEventListener("deviceready", getList, false);
}
$scope.getAll = function(){
$http({
url: 'http://10.0.0.2:63414/myWebMethod/' + $scope.Id,
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.list = data;
});
}
function getList(){
var db = window.openDatabase("Database", "1.0", "list", 200000);
var network = navigator.connection.type;
if (network == "none"){
// local database transaction works fine
} else {
$scope.getAll();
}
$scope.$apply();
}
$scope.init();
}
In the success callback you also have to trigger the digest with $scope.$apply();
$http({
url: 'http://10.0.0.2:63414/myWebMethod/' + $scope.Id,
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.list = data;
$scope.$apply();
});
$http requests are asynchronous, so before you get any response from your request the program will keep executing and $scope.$apply() that you put after the if (network == "none") statement will run for nothing (you can remove it).
The PhoneGap query is working because you are using $scope.$apply() in it's callback, and you have to do the same in the $http success callback.
Related
If the URL that is to be hit has to be passed variables i.e.
API.openweathermap.org/data/2.5/forecast/city?name=[random_city_name]&APPID=[key_value],
then what is better to use ajax or angular js.
If I am using ajax then how am I supposed to pass the variable? I am a newbie in this. So, need your help.
Your url seems to have request parameters and assuming you are using angular1
For this, you can use
$http({
method: 'GET',
url: url,
headers: {},
params : {}
})
Put your parameters as a map and $http will take care of creating an url.
Refer $http documentation here
what is better to use ajax or angular js
You can't compare as AJAX provides a way to communicate (send requests and get responses) with the server asynchronously and AngularJS used AJAX to extends the 2-way data binding.
To accomplish the above situation we can use Angular $http service.
var baseUrl = API.openweathermap.org/data/2.5/forecast/city;
var method = 'GET';
var data = {};
var params = {
"name":cityName,
"APPID":key_value
};
$http({
method: method,
url: baseUrl,
params : params,
data : data
}).then(function mySucces(response) {
$scope.data = response.data;
}, function myError(response) {
$scope.data = response.statusText;
});
You can use angular $http service and pass your params like below.
var UserInfo = function() {
$scope.userID = "1111";
var req ={
"method":"GET",
"url": someURL + $scope.userID,
"withCredentials":true
};
$http(req).then(function(response) {
alert('success');
}, function(response) {
alert('error');
});
};
I am trying to submit a form data to an API endpoint which I created. I have tested it in PostMan and the API functions well and I can get the data in successfully. But while connecting that API endpoint to a function in angular js I get the following error.
Heres my code:
$scope.saveSession = function() {
$http.post("/session/survey", $scope.session).success(function(data, status) {
$window.location.href = '/';
console.log("Sucessfully getting data" + JSON.stringify(data));
})
}
Note:
$scope.session is an object that being populated by using the ng-model tag.
For example:
<input type="text" ng-model="session.title">
Edit (Controller Code):
// This is our controller for the bio page
var session = angular.module('session', ['sessionService'])
session.controller('sessionCtrl', function($scope, $http, $window, sessionServices) {
$scope.session = {};
$scope.saveSession = function() {
$scope.session.sessionNo = 1;
$scope.session.coach = "mmmm";
$scope.session.modules = "wokr place";
//console.log(user);
$http.post("/session/survey", $scope.session).success(function(data, status) {
$window.location.href = '/';
console.log("Sucessfully getting added bio" + JSON.stringify(data));
})
};
});
That's because .success() really isn't a function. As the documentation explains, a promise is returned by $http.post() which you can chain with .then()
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Use promises, "success" function doesn't exists in $http object($http success and error methods are available only in older versions of Angular 1.x, but they've removed in Angular 1.6):
// 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 in official documentation https://docs.angularjs.org/api/ng/service/$http
It's because you're using $http.post().success.
Try;
$scope.saveSession = function() {
$http.post("/session/survey", $scope.session).then(function(data, status) {
$window.location.href = '/';
console.log("Sucessfully getting data" + JSON.stringify(data));
})
}
We use .then to return a "promise" from the $http service.
Hope it helps!
I just dealt with a similar issue with versions 1.7.2 and 1.7.4. It's not exactly the same issue because I was never using .success but I'm posting here because this post comes up first when searching.
When using the shortcut version $http.post(/api/endpoint/', data) I would get:
"TypeError: $http.post is not a function"
And if I used it with the callbacks exactly as it appears in the documentation:
$http({method: 'POST', url: '/api/endpoint/', data: $scope.newObject}).then(function (response) {
$scope.status = response.status;
$scope.data = response.data;
}, function (response) {
$scope.data = response.data || 'Request failed';
$scope.status = response.status;
});
I was getting
"TypeError: $http(...).then is not a function"
In this case the problem was that I had both $resource and $http in the same controller. Not sure if this is the intended behavior but removing $resource suddenly made $http work again.
Hopefully this helps someone else
Im trying to post a api using for my registration page and i have used $HTTP request to post data
it('login page to patient dashboard with existing email and password', function() {
console.log('entering login page')
browser.get('http://localhost:9000/login.html');
browser.executeScript(function(callback) {
var $http;
$http = angular.injector(["ng"]).get("$http");
console.log('http request')
return $http({
url: "http://int.eclinic247.com/reg/create-patient",
method: "post",
data: {"firstName":"jya","lastName":"raq"},
dataType: "json"
}).success(function() {
return callback([true]);
console.log('done')
}).error(function(data, status) {
return callback([false, data, status]);
console.log('oops not done!!!!')
});
})
element(by.model(Objects.locators.passwordBox)).sendKeys(Objects.login.password);
I see that the executeScript block doesnot run and there are no errors too...and the test case passes
Is this the way to post a http request using protractor...Please suggest me the proper to post a data to back-end directly
Any help is much appreciated...Thanks in advance
I have the services and within particular time duration if response is come than ok, other wise show error in popup.
Here is my service code:
angular.module('server', [])
.factory('api', function($http) {
var server = "http://myapi-nethealth.azurewebsites.net";
return {
//Login
login : function(formdata) {
return $http({
method: 'POST',
url: server + '/Users/Login',
data: $.param(formdata),
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
})
},
};
});
Please tell me how can I use timeout property in services.
Read this post - How to set a global http timeout in AngularJs
Where you can set a timeout for your http calls.
You can inject the above factory in your controller and then make a call with success and error callbacks like below
api.login(formdata)
.success(function(){ alert("success"); })
.error(function(){ alert("error"); });
How can I update the common HTTP headers at runtime from an AngularJS controller, e.g. $httpProvider.defaults.headers.common['Authorization']? It seems $httpProvider can only be accessed from a config module, but I need to update common HTTP headers for all future requests from a controller, or a service called by the controller.
I can update the locally scoped headers for the next request by injecting $http into my controller, but I need to do update HTTP headers for all future requests, specifically for basic authentication.
Not sure exactly when it appeared in Angular, but a good 20 months later, you have the option to define default headers at runtime, directly on the $http object.
From $http documentation: Setting HTTP Headers
$http.defaults.headers.common.Authorization = 'Basic dXNlcjpwYXNzd29yZA=='
I used this strategy once when I had to work with an API. I created an XYZApiService to wrap all the requests to that API.
Here's a simple example:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, HttpWrapper) {
$scope.movies = [];
HttpWrapper.setAuthorization('Basic dXNlcjpwYXNzd29yZA==');
HttpWrapper.http({
method: 'get',
url: 'movies.json'
}, function(data, status){
$scope.movies = data;
}, function(data, status){
console.log('error', data, status);
})
});
app.run();
app.factory('HttpWrapper', function($http) {
var authorization = null;
return {
setAuthorization: function(auth){
authorization = auth;
},
http: function(options, successCallback, errorCallback){
if(authorization){
options.headers = options.headers || {};
options.headers.authorization = authorization;
}
console.log(options);
$http(options).success(successCallback).error(errorCallback);
}
}
});
You can try it in Plunker here:
http://plnkr.co/edit/hr2Rvojic0asvWxSoalo?p=preview