Packaged .net-core electron app does not run - asp.net-core

I am trying to create an electron app using .net-core. It is working good in all steps and there are no errors when I test and debug the apps at all.
But unfortunately, when I am packaging the app using electron-packager, I get this error when executing the .exe file.
A javaScript error occurred in the main process Uncaught Exception:
TypeError [ERR_INVALID_ARG_VALUE]: The argument 'args' in invalid.
Received {cwd:
'D:\win\release-builds\gen\resources\app.asar\bin'}
at Object.execFile (child_process.js:218:11)
at Object.module.(anonymous function) as execFile
at exec(child_process.js:160:18)
at ELECTRON_ASAR.js:746:23
at portfinder (D:\win\release-builds\gen\resources\app.asar\main.js:122:22)
at listen D:....
at Server.server.listen D:....
at Object.onceWrapper (events.js:273:13)
at Server.emit (events.js:182:13)
at emitListeningNT (net.js:1364:10)
Here is my main.js file's contents:
(function() {
var childProcess = require("child_process");
var oldSpawn = childProcess.spawn;
function mySpawn() {
console.log('spawn called');
console.log(arguments);
var result = oldSpawn.apply(this, arguments);
return result;
}
childProcess.spawn = mySpawn;
})();
const { app } = require('electron');
const { BrowserWindow, dialog, shell } = require('electron');
const fs = require('fs');
const path = require('path');
const process1 = require('child_process').exec;
const portfinder = require('detect-port');
let io, browserWindows, ipc, apiProcess, loadURL;
let appApi, menu, dialogApi, notification, tray, webContents;
let globalShortcut, shellApi, screen, clipboard;
let splashScreen, mainWindowId;
process.env.NODE_ENV = 'development';
const manifestJsonFilePath = path.join(__dirname, 'bin', 'electron.manifest.json');
const manifestJsonFile = require(manifestJsonFilePath);
if (manifestJsonFile.singleInstance) {
const shouldQuit = app.requestSingleInstanceLock();
app.on('second-instance', (commandLine, workingDirectory) => {
mainWindowId && BrowserWindow.fromId(mainWindowId) && BrowserWindow.fromId(mainWindowId).show();
});
if (shouldQuit) {
app.quit();
}
}
app.on('ready', () => {
if (isSplashScreenEnabled()) {
startSplashScreen();
}
portfinder(8000, (error, port) => {
startSocketApiBridge(port);
});
});
function isSplashScreenEnabled() {
return Boolean(manifestJsonFile.loadingUrl);
}
function startSplashScreen() {
let loadingUrl = manifestJsonFile.loadingUrl;
let icon = manifestJsonFile.icon;
if (loadingUrl) {
splashScreen = new BrowserWindow({
width: manifestJsonFile.width,
height: manifestJsonFile.height,
transparent: true,
frame: false,
show: false,
icon: path.join(__dirname, icon)
});
if (manifestJsonFile.devTools) {
splashScreen.webContents.openDevTools();
}
splashScreen.loadURL(loadingUrl);
splashScreen.once('ready-to-show', () => {
splashScreen.show();
});
splashScreen.on('closed', () => {
splashScreen = null;
});
}
}
function startSocketApiBridge(port) {
io = require('socket.io')(port);
startAspCoreBackend(port);
io.on('connection', (socket) => {
global['electronsocket'] = socket;
global['electronsocket'].setMaxListeners(0);
console.log('ASP.NET Core Application connected...', 'global.electronsocket', global['electronsocket'].id, new Date());
appApi = require('./api/app')(socket, app);
browserWindows = require('./api/browserWindows')(socket, app);
ipc = require('./api/ipc')(socket);
menu = require('./api/menu')(socket);
dialogApi = require('./api/dialog')(socket);
notification = require('./api/notification')(socket);
tray = require('./api/tray')(socket);
webContents = require('./api/webContents')(socket);
globalShortcut = require('./api/globalShortcut')(socket);
shellApi = require('./api/shell')(socket);
screen = require('./api/screen')(socket);
clipboard = require('./api/clipboard')(socket);
if (splashScreen && !splashScreen.isDestroyed()) {
splashScreen.close();
}
});
}
function startAspCoreBackend(electronPort) {
portfinder(8000, (error, electronWebPort) => {
loadURL = `http://localhost:${electronWebPort}`
const parameters = [`/electronPort=${electronPort}`, `/electronWebPort=${electronWebPort}`];
let binaryFile = manifestJsonFile.executable;
const os = require('os');
if (os.platform() === 'win32') {
binaryFile = binaryFile + '.exe';
}
const binFilePath = path.join(__dirname, 'bin', binaryFile);
var options = { cwd: path.join(__dirname, 'bin') };
apiProcess = process1(binFilePath, parameters, options);
apiProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data.toString()}`);
});
});
}
the package.json file's contents:
{
"name": "XXXXXXXX",
"version": "1.0.0",
"description": "XXXXXXXXXXXXXXXXXXX",
"main": "main.js",
"author": "Gregor Biswanger",
"license": "MIT",
"scripts": {
"start": "electron .",
"package-mac": "electron-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds",
"package-win": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Electron Tutorial App\"",
"package-linux": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=linux --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds"
},
"dependencies": {
"detect-port": "^1.2.3",
"socket.io": "^2.1.1"
},
"devDependencies": {
"#types/node": "^10.11.0",
"#types/socket.io": "^1.4.38",
"electron": "^3.1.13",
"electron-packager": "^14.0.4",
"tslint": "^5.11.0",
"typescript": "^3.0.3"
},
"keywords": [
"genetic"
]
}
and the program.cs file:
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseElectron(args)
.Build();
}

Related

How to implement the Music Metadata Or Music MetaData Browser npm plugin in Cypress V10?

I tried to implement the Node plugin in Cypress Version 10, But I couldn't done it.
https://www.npmjs.com/package/music-metadata-browser#fetchurl-function
Installation is done:
npm install --save-dev music-metadata-browser
npm install --save-dev util
Added the below lines in plugin/index.js
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
};
Added the below code in e2e/validateFile.cy.js
describe('Parsing File', () => {
it('Validating Audio File', () => {
const audioURL = 'cypress/fixtures/media/Patrikios.mp3';
console.log('url: ' + audioURL);
cy.task('validateAudioFormat', audioURL).then(data => {
const allData = Object.values(data);
console.log('All data: ' + allData);
});
/******
cy.on('validateAudioFormat', (url) => {
async () => {
const metadata = await mm.fetchFromUrl(url);
console.log('url: ' + url);
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
};
});
*****/
});
});
Error:
CypressError: `cy.task('validateAudioFormat')` failed with the following error:
The task 'validateAudioFormat' was not handled in the setupNodeEvents method. The following tasks are registered: resetCoverage, combineCoverage, coverageReport
Fix this in your setupNodeEvents method here: /opt/lampp/htdocs/project/cypress.config.js
Commented block error:
taskreadAudioFiles, cypress/fixtures/media/audios/valid/Beyond_Patrick_Patrikios.mp3
CypressError
cy.task('readAudioFiles') timed out after waiting 60000ms
Anyone can help on this scenario?
Thanks!
Your project is a mixture of Cypress v9 config and Cypress v10 tests.
I presume you are on 10+ so the plugins now go in cypress.config.js
const { defineConfig } = require('cypress')
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
},
}
})

Nextjs API inaccessiable in production

I am trying to host a NextJS app and everything seems to be working fine locally. I am able to get the data from the site and I can go to the site and see the raw json that is being returned, but when I try to get things working on production the API is completely inaccessible through the browser and through the Axios requests.
The server just returns 500 or Internal Server Error.
I have tried deploying on DigitalOcean App Platform and AWS Amplify, but both fail to connect to the API routes.
I followed this tutorial for the NextJS SSR method that says to build and start using
// next.config.js
const path = require('path')
const Dotenv = require('dotenv-webpack')
require('dotenv').config()
module.exports = {
webpack: (config) => {
config.plugins = config.plugins || []
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true
})
]
return config
},
sassOptions: {
includePaths: [path.join(__dirname, 'styles')]
}
}
// package.json
...
"scripts": {
"dev": "next dev",
"build": "next build",
"digitalocean": "next start -H 0.0.0.0 -p ${PORT:-8080}",
"start": "next start"
},
...
// api.js
const axios = require('axios')
const {getS3URL} = require('./aws')
require('dotenv').config()
export default async (req, res) => {
const config = {
bucket: 'bucket',
key: 'folder/data.json'
}
const request = await axios.get(await getS3URL(config));
try {
res.status(200).json(JSON.stringify(request.data))
} catch {
res.status(500).json({ error: '500', response })
res.status(400).json({ error: '400', response })
}
}
// frontend.js
...
const getData = async () => {
console.log(`${host}api/daily-trip-stats`)
const trips = await axios.get(`${host}api/daily-trip-stats`)
const routes = await axios.get(`${host}api/daily-route-stats`)
const stops = await axios.get(`${host}api/daily-stops-routes`)
const cleanUp = async (data) => {
return await data.map(fea => fea.properties)
}
return {
routes: await cleanUp(routes.data.features),
trips: await cleanUp(trips.data.features),
stops: await cleanUp(stops.data.features)
}
};
...
Checked the server logs and found that the default region was not being set properly.
var { S3Client, GetObjectCommand, Config} = require('#aws-sdk/client-s3');
import { getSignedUrl } from "#aws-sdk/s3-request-presigner";
const getS3URL = async ({bucket, key}) => {
const client = new S3Client({
region: 'us-east-1' // !!! FORGOT TO SET THE DEFAULT REGION
})
var params = {
Bucket: bucket,
Key: key,
Expires: 60,
ContentType: 'blob'
};
const s3Data = new GetObjectCommand(params);
const url = await getSignedUrl(client, s3Data, { expiresIn: 3600 });
return url
};
module.exports = {getS3URL}

Restarting express server in esbuild

I am trying to create a simple express server with esbuild. These are my code
import express from "express";
const app = express();
const port = 3000;
const stopServer = {
stop: () => {},
};
export const createServer = async () => {
app.get("/", async (req, res) => {
res.json({
first: "Hello",
});
});
const server = app.listen(port, () => {
console.log(`Listening on port: ${port}`);
});
stopServer.stop = () => {
server.close();
};
};
export const stop = () => {
stopServer.stop();
stopServer.stop = () => {};
};
esbuild.config.js
const esbuild = require("esbuild");
const path = require("path");
const restartPlugin = () => {
return {
name: "restart-express",
setup(build) {
build.onEnd(async (res) => {
const { stop, createServer } = await import("../dist/server.js");
stop();
createServer();
});
},
};
};
const run = async () => {
await esbuild.build({
entryPoints: [path.resolve(__dirname, "../src/server.ts")],
outdir: path.resolve(__dirname, "../dist"),
platform: "node",
sourcemap: true,
format: "cjs",
watch: {
onRebuild: async (err, res) => {
if (err) {
console.error(err);
} else {
console.log("There is some change");
}
},
},
plugins: [restartPlugin()],
});
};
run();
Reference for plugin : https://github.com/evanw/esbuild/issues/1258#issuecomment-834676530
If you were to run this application It i will work initially but when you change the code, the server wont get updated even if you refresh the page.
I am not really sure where I am making mistake, Any help please
The problem is that node cache the import("..dist/server.js"), as a result it will never return new module. To solve this problem we will write a function
const purgeAppRequireCache = (buildPath) => {
for (let key in require.cache) {
if (key.startsWith(buildPath)) {
delete require.cache[key];
}
}
};
Which will remove the cache from the node. We can also use this function in this manner. Which solves my problem
const esbuild = require("esbuild");
const path = require("path");
const startPlugin = () => {
return {
name: "startPlugin",
setup(build) {
build.onEnd((res) => {
const serverPath = path.resolve(__dirname, "../dist/server.js");
const { stop } = require("../dist/server.js");
stop();
purgeAppRequireCache(serverPath);
purgeAppRequireCache(path.resolve(__dirname, "../src"));
const { listen } = require("../dist/server");
listen();
});
},
};
};
const run = async () => {
await esbuild.build({
entryPoints: [path.resolve(__dirname, "../src/server.tsx")],
outdir: path.resolve(__dirname, "../dist"),
platform: "node",
sourcemap: true,
format: "cjs",
watch: true,
bundle: true,
plugins: [startPlugin()],
});
};
run();
const purgeAppRequireCache = (buildPath) => {
for (let key in require.cache) {
if (key.startsWith(buildPath)) {
delete require.cache[key];
}
}
};
If you not reload runtime, the global's object and sub require(xxx) maby have same error.
You can use kill and fork cluster when change you code, it's same fast like require(xxx), there have example codes: https://github.com/ymzuiku/bike/blob/master/lib/index.js
If you need see kill and fork cluster example, here's a same feature package, also use esbuild, but it use fs.watch: https://www.npmjs.com/package/bike
Hope there could help you :)
#es-exec/esbuild-plugin-serve or #es-exec/esbuild-plugin-start are two alternative esbuild plugins that you can try. They run your bundles or any command line script for you after building your project (supports watch mode for rebuilding on file changes).
The documentation can be found at the following:
#es-exec/esbuild-plugin-serve
#es-exec/esbuild-plugin-start
Disclaimer: I am the author of these packages.

APNS error transmitting to device XXXXXXXXXXXXXX with status 400 and reason BadDeviceToken

I'm trying to set up Push Notifications for RN app using Parse Server as backend. Android works correctly, but iOS tells "APNS error transmitting to device XXXXXXXXXXXXXX with status 400 and reason BadDeviceToken"
Installation class receive device token and all data that I send. Device token is taken from
let deviceToken;
PushNotificationIOS.addEventListener('register', token => {
deviceToken = token
});
...
async function setInstallationObject(donorId) {
let installationController =
Parse.CoreManager.getInstallationController();
installationController
.currentInstallationId()
.then(function(iid) {
let installationObject = Parse.Object.extend('_Installation');
const installation = new installationObject();
installation.set('GCMSenderId', 'xxxxxxxx');
installation.set('installationId', iid);
installation.set('deviceType', iOS ? 'ios' : 'android');
installation.set('appName', 'MMB');
installation.set('appIdentifier', DeviceInfo.getBundleId());
installation.set('channels', []);
installation.set('timeZone', 'america/los_angeles');
installation.set('pushType', iOS ? 'APN' : 'GCM');
installation.set('appVersion', DeviceInfo.getVersion());
installation.set('deviceToken', deviceToken);
installation.set('donorId', donorId);
installation
.save()
.then(() => {})
.catch(() => {});
}).catch(() => {});
}
Parse is configured with token-based authentication(.p8), the token is working on Firebase(I received a test Push Notification), so I exclude version that the trouble in my key.
Doesn't matter what environment I using, prod or dev, I can't see the notifications on each of them.
Parse configurations
const express = require('express');
const ParseServer = require('parse-server').ParseServer;
const ParseDashboard = require('parse-dashboard');
const PushAdapter = require('#parse/push-adapter').default;
const path = require('path');
const scheming = require('./helpers/scheming.js');
require('dotenv').config();
const databaseUri = process.env.DATABASE_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to
localhost.');
}
const pushOptions = {
ios: {
token: {
key: process.env.IOS_key,
keyId: process.env.IOS_keyId,
teamId: process.env.IOS_teamId
},
topic: process.env.IOS_BundleId,
production: process.env.IOS_production
},
android: {
apiKey: process.env.Android_APIkey
}
};
const api = new ParseServer({
databaseURI: databaseUri,
cloud: __dirname+'/cloud/main.js',
appId: process.env.APP_ID,
masterKey: process.env.MASTER_KEY,
serverURL: process.env.SERVER_URL,
publicServerURL: process.env.SERVER_URL,
appName: process.env.APP_NAME,
push: {
adapter: new PushAdapter(pushOptions)
}
});
const dashboardConfig = {
'allowInsecureHTTP': true,
'trustProxy': 1,
'apps': [{
appId: process.env.APP_ID,
masterKey: process.env.MASTER_KEY,
serverURL: process.env.SERVER_URL,
appName: process.env.APP_NAME
}],
'users': [
{
'user': process.env.ParseDashboardLogin,
'pass': process.env.ParseDashboardPass
}
]
};
Packages on server
"dependencies": {
"#parse/push-adapter": "^3.2.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mailgun-js": "^0.22.0",
"moment": "^2.24.0",
"moment-business-days": "^1.1.3",
"parse": "^2.8.0",
"parse-dashboard": "^2.0.5",
"parse-server": "^3.9.0",
"twilio": "^3.37.0"
},
"devDependencies": {
"csv-parser": "^2.3.2"
}

ionic 3 with JWT Authentication login Error

I built an API with symfony, and all is working fine in the browser, but when I try on my device (Android) I get an error 'Server error', is it a problem of compatibility I post my code, please Help!
Login in provider :
login(credentials: CredentialsModel) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({headers: headers});
let body = "_username=" + credentials._username + "&_password=" + credentials._password;
return this.http.post(this.cfg.apiUrl + this.cfg.user.login, body, options)
.toPromise()
.then(data => {
let rs = data.json();
this.saveData(data);
this.idToken = rs.token;
this.scheduleRefresh();
})
.catch((err: any) => this.handleError(err));
}
Function handleError :
protected handleError(error: any): Observable<any> {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.log(errMsg);
return Observable.throw(errMsg);
}
Package json :
{
"name": "maquinas",
"version": "0.0.1",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"#angular/animations": "5.2.10",
"#angular/common": "5.2.10",
"#angular/compiler": "5.2.10",
"#angular/compiler-cli": "5.2.10",
"#angular/core": "5.2.10",
"#angular/forms": "5.2.10",
"#angular/http": "5.2.10",
"#angular/platform-browser": "5.2.10",
"#angular/platform-browser-dynamic": "5.2.10",
"#ionic-native/core": "4.7.0",
"#ionic-native/splash-screen": "4.7.0",
"#ionic-native/status-bar": "4.7.0",
"#ionic/pro": "1.0.20",
"#ionic/storage": "2.1.3",
"#ngx-translate/core": "^10.0.1",
"#ngx-translate/http-loader": "^3.0.1",
"angular2-jwt": "^0.2.3",
"ionic-angular": "3.9.2",
"ionicons": "3.0.0",
"rxjs": "5.5.10",
"sw-toolbox": "3.6.0",
"zone.js": "0.8.26"
},
"devDependencies": {
"#ionic/app-scripts": "3.1.9",
"typescript": "~2.6.2"
},
"description": "An Ionic project"
}
Auth Provider:
import {Injectable} from '#angular/core';
import {Http, Headers, RequestOptions} from '#angular/http';
import {Storage} from '#ionic/storage';
import 'rxjs/add/operator/toPromise';
import {UserModel} from '../models/user.model';
import {CredentialsModel} from '../models/credentials.model';
import {AuthHttp, JwtHelper, tokenNotExpired} from 'angular2-jwt';
import {Observable} from 'rxjs/Rx';
import * as AppConfig from '../app/config';
#Injectable()
export class AuthService {
private cfg: any;
idToken: string;
refreshSubscription: any;
constructor(
private storage: Storage,
private http: Http,
private jwtHelper:JwtHelper,
private authHttp: AuthHttp) {
this.cfg = AppConfig.cfg;
this.storage.get('id_token').then(token => {
this.idToken = token;
});
}
register(userData: UserModel) {
return this.http.post(this.cfg.apiUrl + this.cfg.user.register, userData)
.toPromise()
.then(data => {
this.saveData(data)
let rs = data.json();
this.idToken = rs.token;
this.scheduleRefresh();
})
.catch(e => console.log("reg error", e));
}
login(credentials: CredentialsModel) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({headers: headers});
let body = "_username=" + credentials._username + "&_password=" + credentials._password;
return this.http.post(this.cfg.apiUrl + this.cfg.user.login, body, options)
.toPromise()
.then(data => {
let rs = data.json();
this.saveData(data);
this.idToken = rs.token;
this.scheduleRefresh();
})
.catch((err: any) => this.handleError(err));
}
protected handleError(error: any): Observable<any> {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.log(errMsg);
return Observable.throw(errMsg);
}
saveData(data: any) {
let rs = data.json();
this.storage.set("user", rs.user);
this.storage.set("id_token", rs.token);
}
logout() {
// stop function of auto refesh
this.unscheduleRefresh();
this.storage.remove('user');
this.storage.remove('id_token');
}
isValid() {
return tokenNotExpired();
}
public getNewJwt() {
// Get a new JWT from Auth0 using the refresh token saved
// in local storage
this.storage.get("id_token").then((thetoken)=>{
let senddata: { Token:string} = {
Token : thetoken
};
this.http.get(this.cfg.apiUrl + this.cfg.user.refresh+"?Token="+thetoken)
.map(res => res.json())
.subscribe(res => {
console.log(JSON.stringify(res));
console.log(res.status);
// If the API returned a successful response, mark the user as logged in
// this need to be fixed on Laravel project to retun the New Token ;
if(res.status == 'success') {
this.storage.set("id_token", res.token);
} else {
console.log("The Token Black Listed");
this.logout();
}
}, err => {
console.error('ERROR', err);
});
});
}
public scheduleRefresh() {
// If the user is authenticated, use the token stream
// provided by angular2-jwt and flatMap the token
let source = Observable.of(this.idToken).flatMap(
token => {
// The delay to generate in this case is the difference
// between the expiry time and the issued at time
let jwtIat = this.jwtHelper.decodeToken(token).iat;
let jwtExp = this.jwtHelper.decodeToken(token).exp;
let iat = new Date(0);
let exp = new Date(0);
let delay = (exp.setUTCSeconds(jwtExp) - iat.setUTCSeconds(jwtIat));
console.log("will start refresh after :",(delay/1000)/60);
if(delay-1000<=0)
delay = 1;
return Observable.interval(delay);
});
this.refreshSubscription = source.subscribe(() => {
this.getNewJwt();
});
}
public startupTokenRefresh() {
// If the user is authenticated, use the token stream
// provided by angular2-jwt and flatMap the token
this.storage.get("id_token").then((thetoken)=>{
if(thetoken){
let source = Observable.of(thetoken).flatMap(
token => {
// Get the expiry time to generate
// a delay in milliseconds
let now: number = new Date().valueOf();
let jwtExp: number = this.jwtHelper.decodeToken(token).exp;
let exp: Date = new Date(0);
exp.setUTCSeconds(jwtExp);
let delay: number = exp.valueOf() - now;
if(delay <= 0) {
delay=1;
}
// Use the delay in a timer to
// run the refresh at the proper time
return Observable.timer(delay);
});
// Once the delay time from above is
// reached, get a new JWT and schedule
// additional refreshes
source.subscribe(() => {
this.getNewJwt();
this.scheduleRefresh();
});
}else{
//there is no user logined
console.info("there is no user logined ");
}
});
}
public unscheduleRefresh() {
// Unsubscribe fromt the refresh
if (this.refreshSubscription) {
this.refreshSubscription.unsubscribe();
}
}
}
In the browser works fine, but in android no, please some help!
Replace let rs = data.json();
With let rs = data.text()();