ionic push notification implementation - angularjs

I am implementing push notification my push notification with ionic platform (ionic io) working properly now I have to take out that device token and send it to my server.
below is my ap.js code:
var push = new Ionic.Push({
"debug": true
});
push.register(function(token) {
console.log("My Device token:",token.token);
push.saveToken(token); // persist the token in the Ionic Platform
});
This is my login for
$scope.login = function () {
$http({
method: "post",
url: "http://200.189.253.200:8081/employee-connect/oauth/token",
data: "username="+$scope.username+"&password="+$scope.password+"&grant_type=password&scope=read write&client_secret=my-secret-token-to-change-in-production&client_id=employeeConnectapp2",
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function (data){
window.localStorage.setItem("token_type", data.token_type);
window.localStorage.setItem("token", data.access_token);
$state.go('tabsController.home');
})
.error(function(data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
In the success call I have to send token by fetching it from console but don't know how to do. Kindly help me.

Install this plugin
cordova plugin add https://github.com/phonegap-build/PushPlugin.git
and inside your .run funtion do this
var androidConfig = {
"senderID": "xxxxxxxx", //you should place your gcm project number
};
document.addEventListener("deviceready", function(){
$cordovaPush.register(androidConfig).then(function(result) {
// Success
}, function(err) {
// Error
})
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
//here you will see the device token in alert.
MyService.setDeviceID(notification.regid);
//here i have used MyService to access the regiser id inside my controller
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
}, false);
For more information of getting device id look this
Look this answer that i have posted to get the Deal with GCM push notification Ionic Push Notifications: getPushPlugin is undefined

Related

Passing $scope through AJAX, but only few variables inserted

I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed

satellizer then not called after authentication

I'm very new to angular, so my knowledge is based on tutorials and even then I don't succeed.
I need to authenticate using a google account. That works, I get a token where my api calls could be authorized with. But after login the pop up window should dismiss and I should be redirected to the homepage. This doesn't work.
this is my controller
angular.module('MyApp').controller('loginController', ['$scope', '$auth', '$location','loginService', loginController]);
function loginController($scope, $auth, $location, loginService) {
$scope.authenticate = function(provider) {
$auth.authenticate(provider).then(function(data) {
loginService.saveToken(data.data.token);
console.log('You have successfully signed in with ' + provider + '!');
$location.path('http://localhost/#/home');
});
};
};
in app.js I have my configuration. this is not my work but a friend who is an intern as wel as me, he is responsible for a mobile application, where he uses the same function to get his token, and it works.
authProvider.google({
clientId: CLIENT_ID,
redirectUri: 'http://localhost:3000/api/users/signIn'
});
$authProvider.storage = 'localStorage'; // or 'sessionStorage'
$authProvider.loginRedirect = 'http://localhost/#/home';
This is the controller in node where the url is redirected to (google developer console)
router.get('/signIn', function(req, res) {
//console.log(req);
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
if (!err) {
https.get("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + tokens.access_token, function(response) {
// Continuously update stream with data
var body = '';
response.setEncoding('utf8');
response.on('data', function(d) {
body += d;
});
// Data fetched
response.on('end', function() {
var parsed = JSON.parse(body);
// Check if client_id is from the right app
if (parsed.issued_to == '343234242055-vd082vo0o8r8lmfvp1a973736fd98dht.apps.googleusercontent.com') {
User.getGoogleId(parsed.user_id, function(err, user) {
if (err) {
res.status(500).send({
message: 'not authorized app'
});
}
// No user returned, create one
if (!user) {
// Request user info
oauth2Client.setCredentials(tokens);
plus.people.get({
userId: 'me',
auth: oauth2Client
}, function(err, plusUser) {
if (err) res.status(500).send({
message: 'not authorized app'
});
else {
// Create new user
User.create(plusUser.name.givenName, plusUser.name.familyName, (plusUser.name.givenName + "." + plusUser.name.familyName + "#cozmos.be").toLowerCase(), parsed.user_id, function(err, newUser) {
if (err) res.status(500).send({
message: 'not authorized app'
});
else {
res.statusCode = 200;
return res.send({
response: 'Success',
id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
token: tokens.access_token
});
}
});
}
});
} else {
// Return user
res.statusCode = 200;
return res.send({
response: 'Success',
id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
token: tokens.access_token
});
}
});
}
// if not right app, return unauthorized response
else {
res.status(500).send({
message: 'not authorized app'
});
}
});
});
}
});
});
So I login, I get asked to give permission to the application to use my account info, I get a json response where I can see my name, email and token, and that's it
Even within the company where I work, no one could find an answer. So I came with a solution myself. I don't use satellizer anymore.
.when('/access_token=:access_token', {
template: '',
controller: function($window, $http, $location, $rootScope) {
var hash = $location.path().substr(1);
var splitted = hash.split('&');
var params = {};
for (var i = 0; i < splitted.length; i++) {
var param = splitted[i].split('=');
var key = param[0];
var value = param[1];
params[key] = value;
$rootScope.accesstoken = params;
}
console.log(params.access_token);
var json = {
Token: params.access_token
};
$window.localStorage['token'] = params.access_token;
$http.post('http://localhost:3000/api/users/signIn', json).success(function(data, status) {
console.log(data);
}).error(function(err) {
console.log(err);
});
$location.path("/home");
}
/*controller: 'createNewsFeed',
templateUrl: 'homepage.html'*/
}).
So redirect the page by itself. Because the authentication works on the backend side, I can get a access token, which is the only thing I really need for future use of my rest api. I defined a route where, after receiving the json with the token, my browser is manually redirected to with $window.location. So when that page is loaded (not visible for the user, it goes too fast to notice) I analyse the token, save the token, analyse authentication, when that is successful I manually redirect to the homepage.

Authintication Error in Ionic WooCommerce using Angular

I am implementing Woo Commerce Rest API in my Angular/Ionic project on Cordova Platform. While I am making $http request to get product list or any other data, I am getting error Message. Here is my Service code:
angular.module('services.serverRepo', [])
.service("serverRepo",
['$q','$http','errorHandler','$ionicLoading',function($q,$http,errorHandler,$ionicLoading){
var baseUrl="www.abc.com/wc-api/";
var self=this;
this.products=function(){
var deff=$q.defer();
$http({
method:"GET",
url:baseUrl+"v3/products",
headers: {
"Content-Type":"application/JSON",
"oauth_consumer_key":"gjdfjkbgbdhh645h6bh456b45hbhbgdfhgbdfhgbdfhgbhgbdhfghhfhf",
"consumer_secret":"cs_97d74bbf5e9052ee053a05cbb1a53eec19c0847c"
}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
alert('error:- '+objE);
errorHandler.serverErrorhandler(objE);
deff.reject("server Error");
});
return deff.promise;
};
}])
.service('errorHandler',['$q',function($q){
this.serverErrorhandler=function(error){
alert("ERROR ::"+JSON.stringify(error));
console.log("ERROR ::"+JSON.stringify(error));
};
}
])
and in my controller.js file code is:
$scope.rentaldeptt = function(){
//$ionicHistory.clearCache();
serverRepo.products().then(function(objS){
},function(err){
});
}
I am calling $scope.rentaldeptt on a button click. In response I am getting error message
{"data":{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_timestamp parameter is missing"}]},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"www.abc.com/v3/products","headers":{"Accept":"application/json, text/plain, /"},"params":{"oauth_consumer_key":"gjdfjkbgbdhh645h6bh456b45hbhbgdfhgbdfhgbdfhgbhgbdhfghhfhf","consumer_secret":"cs_97d74bbf5e9052ee053a05cbb1a53eec19c0847c"}},"statusText":"Not Found"}
Any Idea what I am doing wrong?
Please try to following steps to resolve the isue,
Here, I have Created the service in angularjs to handle the calling of woocommerce api with the oauth,
angular.module('myapp.restservices', [])
.service("serverRepo",['$q','$http','errorHandler','$ionicLoading',function($q,$http,errorHandler,$ionicLoading){
var self=this;
//Request Url and method
var request = {
url: 'http://www.example.com/wc-api/v3/products',
method: 'GET'
};
//OAuth Protocol authentication parameters
var oauth = new OAuth({
consumer: {
//Consumer Public Key
public: 'ck_50xxxx',
//Consumer Secrete Key
secret: 'cs_b4xxxx'
},
//oauth1.0a protocol signature method
signature_method: 'HMAC-SHA1'
});
//Service Function to get products
this.products=function(){
$ionicLoading.show({
template: '<ion-spinner class="light"></ion-spinner>'
});
//OAuth Parameters to call woocommerce api
var oauth_data = {
oauth_consumer_key: oauth.consumer.public,
oauth_nonce: oauth.getNonce(),
oauth_signature_method: oauth.signature_method,
oauth_timestamp: oauth.getTimeStamp()
};
//Oauth signature
oauth_data.oauth_signature = oauthSignature.generate(request.method,request.url,oauth_data,oauth.consumer.secret );
console.log("Params : "+ JSON.stringify(oauth_data));
var deff=$q.defer();
$http({
method:"GET",
url:request.url,
headers: {
"Content-Type":"application/JSON",
},
params: oauth_data
}).then(function(objS){
$ionicLoading.hide();
alert('Success :- '+JSON.stringify(objS));
},function(objE){
$ionicLoading.hide();
alert('error:- '+JSON.stringify(objE));
errorHandler.serverErrorhandler(objE);
deff.reject("server Error");
});
return deff.promise;
};
}])
.service('errorHandler',['$q',function($q){
this.serverErrorhandler=function(error){
alert("ERROR ::"+JSON.stringify(error));
console.log("ERROR ::"+JSON.stringify(error));
};
}
])
Write controller to call the service function as like follows,
angular.module(myapp.categorycontrollers, [])
.controller('MainCtrl', function($scope,woocommerce) {
//Method to get all Products
$scope.getAllProducts = function(){
woocommerce.products().then(function(objS){
},function(err){
});
}
//calling to function
$scope.getAllProducts();
}
Hopes this will help you !

Post call for search data

Here i need to search name in scroll,for that i send search data query string in get call but i need to that in post.
Here is my server and client controller route and service.Also here i handling search from server side.How to post data which user has been searched ,and pass that to client and server side.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {
},
searchUsers:{
method: 'GET',
}
});
}
]);
Angular controller:
$scope.searchServer = function(searchData){
DetailService.searchUsers({search:searchData},function(response){
}, function(error){
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller:
exports.searchCust = function (req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function (customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.jsonp(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.get(details.searchCust);
app.param('search', details.searchCust);
};
I didn't try it out in all details as it looks like it was copy and pasted together without reading the basics. However, if you want POST requests, you need to set them both in the node-code and the Angular code, see below. What's more, Angular doesn't use JSONP, it uses JSON, so you need to set that. In the searchUsers-resource-call you only implemented the error-branch, so the results would just vanish. You'll find them in $scope.searchResults now.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {},
searchUsers: {
method: 'POST',
}
});
}]);
Angular controller:
$scope.searchServer = function(searchData) {
DetailService.searchUsers({
search: searchData
}, function(response) {
$scope.status = "OK";
$scope.searchResults = response;
}, function(error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller
exports.searchCust = function(req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function(customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.json(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.post(details.searchCust);
app.param('search', details.searchCust);
};

How to return a success or fail code from Node.js to Angularjs

I am building my website with Angularjs and I am testing it with Node js and express. So, I am able to send a json item with information from the contact page form. But, I do not know How to return a success or fail code from Node.js to Angularjs to redirect to a thank you page. Also, I need to know how to send the information to my email and save it to a db and how to add a token for the form. I know that I'm using the MEAN stack. I learn better watch.
Here is my Node js:
var express = require('express');
var app = express();
var formidable = require('formidable');
app.use(express.static(__dirname + '/public')); // navigate to where the app reside
app.get('/', function (request, response) {
response.redirect('Index.html');
});
app.post('/Contact', function (request, response) {
var frm = new formidable.IncomingForm();
frm.parse(request, function(err, formData){
var Name = formData.Name,
Email= formData.Email,
Message = formData.Message;
response.writeHead(200, { "Content-Type": "application/json" });
response.end("{'status:' 200}");
});
});
var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);
and here is my Angularjs:
$scope.submit = function () {
console.log('Im in the controller');
console.log($scope.formData);
$http({
method : 'POST',
url : '/Contact',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/json' }
}).success(function(result, status, headers, config) {
console.log(result);
if(result.status == "???"){
redirectTo: '/Thnkyu';
}
}).error(function(result, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(result);
});
}
When I submit the form; the console showed: TypeError: Cannot read property 'protocol' of undefined Before it showed: ERR_CONNECTION_REFUSED because I had the url portion before I setted the headers and data.
The problem was I use the angularJs $http dependence as shown above; but, it did not work. So, I use the $http dependence like so:
$scope.submit = function () {
console.log($scope.formData);
$http.post("/contact", $scope.formData)
.success(function(reponse){
if(reponse.status == 200)
console.log('im in')
$location.path('/thnkyu');
});
and the response from the server is like this:
...
if(!eor){
console.log(eor);
response.json({status: 200});
}

Resources