Angular and ionicPush not working on android - javascript

Trying to migrate to ionicPush but getting errors anyway I do it:
Option 1 - Angular method
When I put $ionicPush.init as per guide in the app.js or anywhere for that matter, getting:
Uncaught TypeError: $ionicPush.init is not a function
When I check $ionicPush it has 2 methods, register and unregister. So clearly it gets imported, but for whatever reason doesnt have .init
Top of app.js looks like this:
.run(function(AppRootService, $ionicPlatform, $ionicPush, $cordovaSplashscreen,$window, $timeout) {
$ionicPlatform.ready(function() {
$ionicPush.init({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
$ionicPush.register();
Option 2 - Regular JS way
Put this code in app.js after $ionicPlatform.ready()
var push = new Ionic.Push({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
push.register(function(token) {
console.log("Device token:",token.token);
});
Ionic.io();
Still nothing, this time error is Uncaught ReferenceError: Ionic is not defined
Ran both of these:
ionic add ionic-platform-web-client
ionic plugin add phonegap-plugin-push
Moved around Ionic.io(), not luck

I think you have to init io and activate debug/dev mode.
Here is the all steps...
ionic add ionic-platform-web-client
ionic plugin add phonegap-plugin-push
ionic io init
ionic config set dev_push true
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
var push = new Ionic.Push({
"debug": true
});
push.register(function(token) {
console.log("Device token:",token.token);
});
});
})
Checkout this page for setting up push for platforms (iOS, Android)
http://docs.ionic.io/docs/push-from-scratch

This is the code i use with the phonegap-plugin-push
inside the run phase
document.addEventListener("deviceready", function () {
var androidConfig = {
'senderID': '****google-project-id****',
'sound': true,
'vibrate': true
};
var Push = PushNotification.init({
"android": androidConfig
});
Push.on('registration', function(data) {
// device token:
var deviceToken = data.registrationId;
console.log('pushToken', deviceToken);
});
Push.on('error', function(e) {
console.error('Notifications error: ', e.message, e);
});
Push.on('notification', function(response){
console.log('norification', response)
console.log('any additinal data the push recieved', response.additionalData)
});
}, false);
try what i did and it will work for you.

Related

Value not set to global variable in JS/AngularJs

I am using gulp to run and build to run my application. I am getting file contents using $http service in my index.js file and then setting value of a variable like
window.variablex = "http://localhost:8080/appname".
here is how I am doing it (in index.js)
(function ()
{
'use strict';
angular
.module('main')
.controller('IndexController', IndexController);
function IndexController($http){
$http.get('conf/conf.json').success(function(data){
window.variable = data.urlValue;
}).error(function(error){
console.log(error);
});
}
});
And I've created a factory to call the rest APIs of my backend application like
(function(){
'use strict';
angular
.module('main')
.factory('testService',['$resource',testService]);
function agentService($resource){
var agents = $resource('../controller/',{id:'#id'},
{
getList:{
method:'GET',
url:window.variable+"/controller/index/",
isArray:false
}
});
Now, I except a rest call to made like
http://localhost:8080/appname/controller
But it always sends a call like http://undefined/appname/controller which is not correct.
I can get the new set value anywhere else, but this value is not being set in resource service objects somehow.
I am definitely missing something.
Any help would be much appreciated
As you are using Gulp, I advise you to use gulp-ng-config
For example, you have your config.json:
{
"local": {
"EnvironmentConfig": {
"api": "http://localhost/"
}
},
"production": {
"EnvironmentConfig": {
"api": "https://api.production.com/"
}
}
}
Then, the usage in gulpfile is:
gulp.task('config', function () {
gulp.src('config.json')
.pipe(gulpNgConfig('main.config', {
environment: 'production'
}))
.pipe(gulp.dest('.'))
});
You will have this output:
angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});
And then, you have to add that module in your app.js
angular.module('main', [ 'main.config' ]);
To use that variable you have to inject in your provider:
angular
.module('main')
.factory('testService', ['$resource', 'EnvironmentConfig', testService]);
function agentService($resource, EnvironmentConfig) {
var agents = $resource('../controller/', {id: '#id'},
{
getList: {
method: 'GET',
url: EnvironmentConfig + "/controller/index/",
isArray: false
}
});
}
#Kenji Mukai's answer did work but I may have to change configuration at run time and there it fails. This is how I achieved it (in case anyone having an issue setting variables before application gets boostrap)
These are the sets that I followed
Remove ng-app="appName" from your html file as this is what causing problem. Angular hits this tag and bootstraps your application before anything else. hence application is bootstratped before loading data from server-side (in my case)
Added the following in my main module
var injector = angular.injector(["ng"]);
var http = injector.get("$http");
return http.get("conf/conf.json").then(function(response){
window.appBaseUrl = response.data.gatewayUrl
}).then(function bootstrapApplication() {
angular.element(document).ready(function() {
angular.bootstrap(document, ["yourModuleName"]);
});
});
This will load/set new values everytime you refresh your page. You can change conf.json file even at runtime and refreshing the page will take care of updating the values.

Handle Push notification in Nativescript

I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});

Kibana Customized Visualization with ES and Angular Doesn't Work

First, I try to make a custom visualization in Kibana with learning here.
Then, I want my custom visualization to display like the clock how many hits my elasticsearch index has dynamically .
So, I changed some codes in above tutorial but they don't work.
Chrome Devtools tells says Error: The elasticsearch npm module is not designed for use in the browser. Please use elasticsearch-browser
I know I had better use elasticsearch-browser perhaps.
However, I want to understand what is wrong or why.
public/myclock.js
define(function(require) {
require('plugins/<my-plugin>/mycss.css');
var module = require('ui/modules').get('<my-plugin>');
module.controller('MyController', function($scope, $timeout) {
var setTime = function() {
$scope.time = Date.now();
$timeout(setTime, 1000);
};
setTime();
var es = function(){
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
client.search({
index: 'myindex',
}).then(function (resp) {
$scope.tot = resp.hits.total;
}, function (err) {
console.trace(err.message);
});
};
es();
});
function MyProvider(Private) {
...
}
require('ui/registry/vis_types').register(MyProvider);
return MyProvider;
});
public/clock.html
<div class="clockVis" ng-controller="MyController">
{{ time | date:vis.params.format }}
{{tot}}
</div>
Thank you for reading.
Looks like the controller in angularjs treats the elasticsearch javascript client as if it was accessing from the browser.
To elude this, one choice will be by building Server API in index.js and then make kibana access to elasticsearch by executing http request.
Example
index.js
// Server API (init func) will call search api of javascript
export default function (kibana) {
return new kibana.Plugin({
require: ['elasticsearch'],
uiExports: {
visTypes: ['plugins/sample/plugin']
},
init( server, options ) {
// API for executing search query to elasticsearch
server.route({
path: '/api/es/search/{index}/{body}',
method: 'GET',
handler(req, reply) {
// Below is the handler which talks to elasticsearch
server.plugins.elasticsearch.callWithRequest(req, 'search', {
index: req.params.index,
body: req.params.body
}).then(function (error, response) {
reply(response);
});
}
});
}
});
}
controller.js
In the controller, you will need to call GET request for above example.
$http.get( url ).then(function(response) {
$scope.data = response.data;
}, function (response){
$scope.err = "request failed";
});
In my case, I used url instead of absolute or relative path since path of dashboard app was deep.
http://[serverip]:5601/iza/app/kibana#/dashboard/[Dashboard Name]
*
Your here
http://[serverip]:5601/iza/[api path]
*
api path will start here
I used this reference as an example.

ionic.bundle.js:25642 Error: [$injector:unpr] Unknown provider: $cordovaGeolocationProvider <- $cordovaGeolocation <- AgeCtrl

I am currently in the starting phase of building an app via Ionic. Right now i want to implement the cordova geolocation in it. However this keeps giving an error when opening it. For testing purposes i use ionic serve and check it in localhost.
angular.module('starter', ['ionic','ionic.service.core', 'ui.router'])
.controller('AgeCtrl', function ($scope, $state, $http, $cordovaGeolocation) {
$scope.toggleItem = function (item) {
item.checked = !item.checked;
};
$scope.items = [
{ id: '0-12' },
{ id: '12-18' },
{ id: '18-30' },
{ id: '30-65' },
{ id: '65+' }
];
$scope.time = Date.now();
$scope.weather = $http.get("http://api.openweathermap.org/data/2.5/weather?q=Amsterdam&units=metric&APPID=...").then(function(resp) {
console.log("success", resp);
}, function(err) {
console.log("error");
})
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
$scope.Confirm = function (){
$state.go('home');
}
})
Is there any place i have made a mistake which causes this problem?
Ionic serve only emulates the application in the browser.
You do not get access to the Cordova plugins within the browser.
To get the libraries included you need to run the app on the device after adding a specific platform depending on what device you have.
For iOS:
Ionic platform add ios
For android:
ionic platform add android
After the platforms are added you can build and run on device using the following command
For iOS:
ionic run iOS
For android:
ionic run android
I believe the issue is with your ngCordova installation .
do below steps -
1- install --------------> bower install ngCordova
2- include in index.html above cordova.js ------------------> script src="lib/ngCordova/dist/ng-cordova.js"
3- inject -------------> angular.module(starter, ['ngCordova'])
run IONIC serve and issue will be gone .. If it still shows error that /dist/ngCordova is not present then go to location manually where ng cordova is installed and copy it to the path e.g. - /lib/ngCordova/dist/...
it will definitely resolve your issue
I think it's not referenced as $cordovaGeolocation in ionic. Try navigator.geolocation.getCurrentPosition instead?

Meteor CollectionFS Collection is Undefined?

I am trying to use CollectionFS and GridFS to upload some images to my app and serve them back.
I have the following definitions:
ImageStore.js:
var imageStore = new FS.Store.GridFS("images", {
mongoUrl: 'mongodb://127.0.0.1:27017/test/',
transformWrite: myTransformWriteFunction,
transformRead: myTransformReadFunction,
maxTries: 1,
chunkSize: 1024*1024
});
EventImages = new FS.Collection("images", {
stores: [imageStore]
});
ImageStorePub.js:
Meteor.publish("EventImages", function() {
return EventImages.find();
});
ImageUploadHandler.js:
if (Meteor.isServer) {
EventImages.allow({
'insert': function() {
// add custom authentication code here
return true;
}
});
}
After typing all of this I tried wrapping them all in a if(Meteor.isServer){...} despite the fact that they're already in my server folder, but my app is still crashing due to error ReferenceError: EventImages is not defined
at server/route handlers/ImageUploadHandler.js:2:1
I made a mistake in not assigning the variable on both the client and server.

Categories

Resources