How to change location and refresh page in angular js - javascript

I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.

If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});

Related

Problem inizialise a global variable AngularJS by calling a REST service

I want to create a global variable (httpTimeout) initialize at the start, contains a Long value returned by a synchrone call Rest Service and used it in different service
(
function () {
'use strict';
angular
.module('module')
.factory('MyService', function (
$http,
$q
){
var service = {};
var httpTimeout = function() {
return $http({
method: 'GET', '.../rest/getHttpTimeOut'
}).then(function (response) {
return response.data;
}).catch(function (err) {
return 30000;
});
};
service.myService1= function (Model) {
return $http({
method: 'POST', '..../rest/callRestService1',
data: Model, timeout : httpTimeout
}).then(function (response) {
return response.data;
});
};
service.myService2= function (Model) {
return $http({
method: 'POST', '..../rest/callRestService2',
data: Model, timeout : httpTimeout
}).then(function (response) {
return response.data;
});
};});
My rest service
#RequestMapping(value = "/getHttpTimeOut", method = RequestMethod.GET)
#ResponseBody
public long getHttpTimeOutValue() {
return timeoutValue;
}
how i can retrieve this value globally (httpTimeout) for use in other services
Thank you for your help
if your question is how to do something on application start :
look at that
After your application start you can use another service to store the value.
Also if you want to apply this comportement for all request take a look to interceptor

Convert JS Post Ajax to AngularJS Post Factory

I am trying to convert an Ajax call with WSSE authentication to an AngularJS factory.
The method is Post.
The intended use of this is to access the Adobe Analytics Rest API and return data to be converted to JSON and then visualised with d3.js.
I am not familiar with the properties that can be used in an AngularJS $http post call and so not sure what is the correct way to do the WSSE auth, dataType, callback etc.
This is the original ajax code which came from a public github repo:
(function($) {
window.MarketingCloud = {
env: {},
wsse: new Wsse(),
/** Make the api request */
/* callback should follow standard jQuery request format:
* function callback(data)
*/
makeRequest: function (username, secret, method, params, endpoint, callback)
{
var headers = MarketingCloud.wsse.generateAuth(username, secret);
var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
$.ajax(url, {
type:'POST',
data: params,
complete: callback,
dataType: "text",
headers: {
'X-WSSE': headers['X-WSSE']
}
});
}
};
})(jQuery);
This is the current way the code is being used with pure JS:
MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
data = JSON.parse(response.responseText);
});
I want to convert this to a factory and a controller respectively.
This is what I have done for the factory so far:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return function(username, secret, method, params, endpoint) {
return $http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
},
dataType: 'text',
});
};
}]);
And this is what I have for the controller:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
mainFactory.success(function(data) {
$scope.data = data;
});
}]);
Currently I get an error saying mainFactory.success is not a function which I assume is because the factory isn't working yet.
I have resolved this question myself. The parameters I was passing to the first function in the factory were globally defined already and therefore getting over-written.
The first function is not required anyway.
Here is the factory code:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return {
getAnalytics : function (){
$http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
}
})
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
And here is the controller code:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
$scope.title = "Inn Site";
$scope.data = mainFactory.getAnalytics();
}]);

Javascript AngularJS: Inner function cannot the variable value of outer function

I am developing ionic hybrid application. I am using $http to get value from server. Next, I will make a cordova sqlite query, inside the cordova query I want to insert my result from $http call from server and result of cordova query into my sqlite database. However, I can't get the value of $http return value in my cordova query. The following is my code:
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
for(i=0; i<response.length; i++){
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [response[i].ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [response[i].LastText, usernameID, response[i].ChannelName, result.rows.item(0).UserName]);
})
}
}).error(function(response) {
console.log(response);
console.log("failed");
});
I can't get response[i].LastText and response[i].ChannelName value inside $cordovaSQLite.execute() function.
Sorry for my poor language.
The data you recive is mapped on response.data. Try looping thru your data by using angular.forEach(). Remember that response is mostly a object so you cant get response.length here. Please take a look at the $http AngularJS documentation.
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
angular.forEach(response.data, function (data) {
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [data.ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [data.LastText, usernameID, data.ChannelName, result.rows.item(0).UserName]);
})
});
}).error(function(response) {
console.log(response);
console.log("failed");
});

Passing Parameter to Angular

I am going to create a controller that will list distinct a selected field in a selected table in database and pass it to my API.
Currently, i am using a dirty method which is create several controller that has the field name and table name in it.
controller.js
.controller('ListDistinctCustomerCtrl', function($scope, $http) {
var xhr = $http({
method: 'post',
url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code'
});
xhr.success(function(data){
$scope.data = data.data;
});
})
.controller('ListDistinctSupplierCtrl', function($scope, $http) {
var xhr = $http({
method: 'post',
url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code'
});
xhr.success(function(data){
$scope.data = data.data;
});
})
and this is the API file
list-distinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT distinct $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
I believe there is a clean and better way to do this.
You can create a service which contains methods for accessing your API. This will enable you to reduce your code duplication in your controllers, and allow for cleaner code in general.
.service('APIService', function($http){
var base = 'http://localhost/api/';
this.listDistinct = function(table, field){
return $http({
method: 'post'
, url: base + '/list-distinct.php'
, params: {
table: table
, field: field
}
});
}
});
Your controllers would inject the service and call whatever method it needs to access the api. Results will be obtained the same way by attaching a promise callback.
.controller('ListCtrl', function($scope, APIService){
APIService.listDistinct('customer', 'cust_code').then(function(data){
$scope.data = data;
})
});
For the PHP side of your code you need to use a white-list of possible table/field names to ensure safe operation. Without such a check you are vulnerable to SQL injection attacks. A simple array check would suffice.
$safeTables = ['customer', 'supplier'];
$safeFields = ['cust_code', 'supp_code'];
if (!in_array($tablename, $safeTables) || !in_array($fieldname, $safeFields)){
throw new Exception('Invalid parameter');
}
first of all, if you want to pass parameters by $http there is a cleaner method:
$http(
{
url: 'your url',
method: 'GET or POST',
params: {
// list of params
}
}
);
Now, is important for code maintenance and readability to use Service provider.
You can use Factory as service and create an API service.
Example:
angular.module( 'yourModule' ).factory( 'ServiceAPI', [ '$http', function ( $http ) {
var factory = {};
//PUBLIC METHODS
factory.method = method;
function method() {
return $http(
{
url: 'your url',
method: 'GET or POST',
params: {
// list of params
}
}
);
}
return factory;
} ] );
And now you can inject ServiceAPI on your Controller and use method function that reply with a promise of http.
angular.module( 'your module' ).controller( 'Ctrl', [ '$scope', 'ServiceAPI' ,
function ( $scope, ServiceAPI ) {
ServiceAPI.method.then( function ( data) {
$scope.data = data;
}, function(){console.err('error');} );
}
] );
AngularJS side, now is clear and readable.
I hope to be helpful for you.
Enjoy
Its time for Angular Providers
This is an example for your case:
angular.module('starter')
.factory('services', services);
function services($http) {
var services = {
customer: customer,
supplier: supplier,
};
return services;
//customer service
function customer() {
var req = {
method: 'POST',
url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code',
headers: {
'Accept' : 'application/json',
'contentType': "application/json"
}
};
return $http(req);
},
//supplier service
function supplier() {
var req = {
method: 'POST,
url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code',
headers: {
'Accept' : 'application/json',
'contentType': "application/json"
}
};
return $http(req);
};
}
Then you call them like this from within the controller:
services.customer().then(
function(response) {
//do whatever is needed with the response
console.log(response);
},
function (error) {
console.log(error);
}
);
services.supplier().then(
function(response) {
//do whatever is needed with the response
console.log(response);
},
function (error) {
console.log(error);
}
);

Angularjs: Singleton service using $http [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is it possible in angular to create service using $http which will take method, url, success and failure callback as parameters when called from controller.
I want to achieve following kind of functionality using angular.
var ajax = {
URL: "webservice url",
loggedIn: false,
importedId: "",
token: '',
userdetails: new Backbone.Collection.extend({}),
serverCall: function(method, data, successCallBack, failureCallBack) {
var that = this;
//console.log(method);
//console.log(successCallBack);
that.showLoading();
$.ajax({
url: that.URL + method,
method: 'post',
data: data,
// contentType:"application/json; charset=utf-8",
success: function(data) {
that.hideLoading();
if (that.checkForError(data))
{
successCallBack(data);
}
},
fail: function(data) {
that.hideLoading();
failureCallBack(data);
}
});
}
i am using https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 folder structure for app and inside services i have following code
define(['./module'], function(services) {
'use strict';
services.factory('user_resources', ['$resource', '$location', function($resource, $location) {
return $resource("", {},
{
'getAll': {method: "GET", url:'JSON/myList.JSON',isArray:true}
});
}]);
});
and in controller i have following code
define(['./module'], function (controllers) {
'use strict';
controllers.controller('myListCtrl',['Phone','Phone1','loginForm','$scope','$http','user_resources','CreditCard',function(Phone,Phone1,loginForm,$scope,$http,user_resources,CreditCard){
console.log(user_resources.getAll())
}]);
});
which returns [$promise: Object, $resolved: false] how to get data from that?
A service in AngularJS is always a singleton, so you wouldn't have to do anything to achieve that. However, it seems like you do not actually want a singleton as you want to pass in different values. Thus, you might want to add your own service factory function. Something like:
function MyHTTPService($rootScope, url, method) {
this.$rootScope = $rootScope;
this.url = URL;
this.method = method;
}
MyHTTPService.prototype.serverCall = function () {
// do server call, using $http and your URL and Method
};
App.factory('MyHTTPService', function ($injector) {
return function(url, method) {
return $injector.instantiate(MyHTTPService,{ url: url, method: method });
};
});
This can be called using
new MyHTTPService("http://my.url.com", "GET");
you could also use $resource for this type of usage.
angular.module('MyApp.services').
factory('User_Resource',["$resource","$location", function ($resource,$location){
var baseUrl = $location.protocol() + "://" + $location.host() + ($location.port() && ":" + $location.port()) + "/";
return $resource(baseUrl+'rest/users/beforebar/:id',{}, {
query: { method: 'GET', isArray: true },
get: { method: 'GET' },
login: { method: 'POST', url:baseUrl+'rest/users/login'},
loginAnonymous: { method: 'POST', url:baseUrl+'rest/users/loginAnonymous'},
logout: { method: 'POST', url:baseUrl+'rest/users/logout/:id'},
register: { method: 'POST', url:baseUrl+'rest/users/register'}
});
}]);
Example of usage :
userSrv.logout = function(user,successFunction,errorFunction)
{
var userSrv = new User_Resource();
userSrv.$logout({user.id}, //params
function (data) { //success
console.log("User.logout - received");
console.log(data);
if (successFunction !=undefined)
successFunction(data);
},
function (data) { //failure
//error handling goes here
console.log("User.logout - error received");
console.log(data);
var errorMessage = "Connexion error";
if (errorFunction !=undefined)
errorFunction(errorMessage);
});
}

Categories

Resources