Angularjs timeout - angularjs

why is this time out not working? I have injected $timeout in controller. Even moving timeout into http response is the same. Using angularjs 1.6.6 with Laravel 5.2. $scope.showInfo is true, but not false after 3000 ms.
$scope.submitAttendance = function(attData) {
$http({
method: 'POST',
url: '/api/save/attendance',
headers: { 'Content-Type' : 'application/json' },
data: attData
}).then(function successCallback(response) {
var response = response.data;
if (response == 1) {
$scope.msg = 'Attendance details saved to system';
$scope.attData = {};
$scope.attData.timeIn = new Date (new Date().toDateString() + ' ' + '08:00');
$scope.attData.timeOut = new Date (new Date().toDateString() + ' ' + '16:00');
} else {
$scope.msg = 'Failed to save Attendance info';
}
}, function errorCallback(response) {
$scope.msg = 'There is a problem saving data at this time. Please contact Administrator';
});
$scope.showInfo = true;
$timeout(function(){ $scope.showinfo = false; }, 3000);
}

Related

getting undefined while sending http post method

I am Passing my user information http angularjs. backend code is PHP
As I am the beginner I am searching lot for this Issue. and tried a lot methods since 2 days but I couldn't find the reason, and how to fix it?. it may be simple but I couldn't find.
1.I am posting my http post request in angularJS I have been debugged the value which I will send is
Debugging value are as follow:
serializedParams:"send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
url: "insert.php?send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
result: undefined
I think the url is correct. but the result is undefined
var app = angular.module("myapp", []);
app.controller("booking", function($scope, $http) {
$scope.paidops = ["Paid", "Due"];
$scope.value = "ADD";
$scope.insertvalues = function() {
alert($scope.id + ' , ' +
$scope.name + ' ,' + $scope.phone +
' , ' + $scope.status);
alert($scope.name);
var Indata = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
method: 'POST',
url: 'insert.php',
params: Indata,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
alert(JSON.stringify(response));
}, function(response) {
alert(response);
});
}
});
In PHP I am getting data like this way:
$connect = mysqli_connect("localhost:3307", "root", "", "ticket_booking");
if($connect === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$data = json_decode(file_get_contents("php://input"),true);
if(count(array($data)) > 0)
{
$id_received = mysqli_real_escape_string($connect, $data->send_id);
$name_received = mysqli_real_escape_string($connect, $data->send_name);
$phone_received = mysqli_real_escape_string($connect, $data->send_phone);
$status_received = mysqli_real_escape_string($connect, $data->send_status);
$btnname_received = mysqli_real_escape_string($connect, $data->send_btnName);
if($btnname_received == 'ADD'){
$query = "INSERT INTO society_tour(id,name, phone, status) VALUES ('$id_received','$name_received', '$phone_received','$status_received')";
if(mysqli_query($connect, $query))
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
}
?>
Not entirely sure about the PHP part, but as you have json_decode in PHP, its safe to assume that PHP expects a JSON content-type
If so, here is how to post data to a url
var postUrl = 'insert.php'; // please check whether the url is correct
var dto = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
url: postUrl,
method: 'POST',
data: dto,
headers: {
"Content-Type": "application/json"
}
})
//...

Set $http timeout on the fly

I have an Angular project that has a very nice Timeout toaster that pops up if requests are too slow. But the problem is I need much longer timeouts or timeout resets during a File upload (im using ng-file-upload to s3 storage).
My question is: How could I reset a $http timeout during each progress responses or change it to some massive number only during file-uploads:
Here is my interceptor code in my config function:
$httpProvider.interceptors.push(function ($rootScope, $q, toaster) {
return {
request: function (config) {
//config.cache = true;
config.timeout = 6000;
return config;
},
responseError: function (rejection) {
//console.log(rejection);
switch (rejection.status) {
case -1 :
console.log('connection timed out!');
toaster.pop({
type: 'error',
title: 'Server Timed Out!',
body: 'Waiting for request timed out! \n Please check your Internet connection and try again!',
timeout: 6000
});
break;
case 404 :
console.log('Error 404 - not found!');
toaster.pop({
type: 'error',
title: 'Server Timed Out!',
body: 'Error 404! \n Server returned: Not found! Please check your Internet connection and try again!',
timeout: 6000
});
break;
}
return $q.reject(rejection);
}
}
})
Here is my Upload function:
$scope.upload = function (file) {
$scope.count += 1;
file.id= $scope.count;
var durl = apiserv + "api.upload-s3.php?path=" + $scope.folder;
var arr = [];
arr.filename = file.name;
arr.status = "";
arr.progress = 0;
arr.class = "list-group-item-warning";
$scope.files[file.id] = arr;
$http({url: durl}).then(function (drs) {
console.log(drs);
drs.data.file = file;
Upload.upload({
url: drs.data.action, //S3 upload url including bucket name
method: 'POST',
data: {
key: drs.data.key,
acl: drs.data.acl,
Policy: drs.data.Policy,
'X-Amz-Algorithm' : drs.data['X-Amz-Algorithm'],
'X-Amz-Credential' : drs.data['X-Amz-Credential'],
'X-Amz-Date' : drs.data['X-Amz-Date'],
'X-Amz-Signature' : drs.data['X-Amz-Signature'],
//'Content-Type': file.type !== '' ? file.type : 'application/octet-stream',
file: file
}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
$scope.files[resp.config.data.file.id].status = "Success";
$scope.files[resp.config.data.file.id].progress = 100;
$scope.files[resp.config.data.file.id].class = "list-group-item-success";
}, function (resp) {
console.log('Error status: ' + resp.status);
$scope.files[resp.config.data.file.id].status = "Error: "+ resp.status;
$scope.files[resp.config.data.file.id].progress = 0;
$scope.files[resp.config.data.file.id].class = "list-group-item-danger";
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
//console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
console.log(evt.config.data.file);
$scope.files[evt.config.data.file.id].status = "Uploading...";
$scope.files[evt.config.data.file.id].progress = progressPercentage;
$scope.files[resp.config.data.file.id].class = "list-group-item-warning";
});
});
};
$http's timeout option accepts promises:
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
This means that it can be a promise that polls global variable
config.timeout = $q(function (resolve) {
var i = 0;
var interval = setInterval(function () {
i++;
if (i * 1000 >= $rootScope.httpTimeout) {
resolve();
$rootScope.$apply();
clearInterval(interval);
});
}, 1000);
});
or implements any other logic that fits the case.

Converting ajax api post to $http post in angular js getting a 404

I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}

IE10 - Page Blank when window.open(trustedURL) - PDF ANGULAR JS

I tried to generate a PDF since data returned from API.
All working find exept for IE 10, Edge which open a blank window ! I dont know what happening...
Controller function :
(fileRequest = User.getFile($rootScope.PARAMS, 'facture', 'arraybuffer')).then(function(dataFactureFile)
{
var file = new Blob([dataFactureFile], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$timeout(function()
{
if(action == 'view')
{
$window.open($scope.content);
}
if(action == 'download')
{
var anchor = document.createElement("a");
anchor.setAttribute('download', false);
anchor.download = 'FACTURE-' + $scope.infosFacture.type + '-' + $scope.infosFacture.date + '.pdf';
anchor.href = $scope.content;
anchor.click();
}
}, 500);
}, function(reason){
if(reason != 'aborted')
{
// REJECT
$scope.popin(reason.errorCode, reason.errorMsg);
}
});
Service :
getFile: function(user, type, type_response)
{
var deferredAbort = $q.defer();
var request = $http({
method: "post",
url: $rootScope.directory + 'api/' + type,
data: user,
headers: {
'Content-Type': 'api/downloadPDF'
},
responseType : type_response,
timeout: deferredAbort.promise
}).then(
function(response) {
return(response.data);
},
function(response) {
return($q.reject('aborted'));
}
);
request.abort = function() {
deferredAbort.resolve();
};
return(request);
},
In addition, the "anchor.click()" seems to not working with IE :/, somebody have a tip for simulate download click ?
Thank's you

Why is the login service not called in AngularJS using $http?

I am trying to call a service using $http service. On button click, I call service but I am getting an error. How do I call the authentication login service in AngularJS?
Here is my code:
$scope.firstrequest = function() {
$scope.data = {};
$scope.data.username = "tob.mob#bbb%%..test";
$scope.data.password = "#1234";
dataa = "username=" + $scope.data.username + "&" + "password=" + $scope.data.password;
console.log('Sign In function called');
if ($scope.data.username && $scope.data.username != "" && $scope.data.password && $scope.data.password != "") {
$http({
method: "post",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: "https://fulldemo3-yuj****",
data: dataa
}).success(function(result) {
alert('---')
// $scope.loader = true;
console.log("result:" + JSON.stringify(result));
$scope.loader = false;
}
}.error(
function(error) {
alert('error')
}));
}
}
You just forget a closing ) in your code
replace:
}.error(
by (just added the )):
}).error(
to solve your problem
UPDATED Plunker: http://plnkr.co/edit/vsAC4c2z0HoIVBMK2fSQ?p=preview

Resources