how to get current url, on exit event InAppBrowser, Ionic2 - ionic2

I am trying to implement a solution where I need to get the current url on exit event of InAppBowser Ionic2.
My Code is
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {InAppBrowser} from 'ionic-native';
#Component({
selector: 'page-list',
templateUrl: 'list.html'
})
export class ListPage {
browser:any;
exit:boolean = false;
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
startPayment(){
this.browser = new InAppBrowser('https://ionic.io', '_blank','location=no,toolbar=no,hardwareback=no,EnableViewPortScale=yes,closebuttoncaption=Done');
this.browser.on("exit")
.subscribe(
(e) => {
this.checkpaymentStatus(e);
},
err => {
console.log("InAppBrowser loadstart Event Error: " + err);
});
};
checkpaymentStatus(e){
console.log(e);
console.log("in app browser exit")
this.exit = true;
}
};//
The exit event is firing properly but I am unable to get the url in event(e), it just gives Object{type:exit}.
Please tell me , how can I get the url on exit.
Thanks

just use e.url
checkpaymentStatus(e){
console.log(e.url); // you will get url here
// ... ... ...
}

Related

Angular app keeps saying message does not exist

I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/
However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the point marked 'this point' in the code.
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { MessageResponse, Channel } from 'stream-chat';
import { StreamService } from '../stream.service';
import { StateService } from '../state.service';
declare const feather: any;
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss'],
})
export class ChatComponent implements OnInit {
constructor(
public streamService: StreamService,
private stateService: StateService,
private router: Router
) {}
messages: MessageResponse[] = [];
message = '';
channel!: Channel;
async sendMessage() {
if (this.message) {
try {
await this.channel.sendMessage({
text: this.message,
});
this.message = '';
} catch (err) {
console.log(err);
}
}
}
getClasses(userId: string): { outgoing: boolean; incoming: boolean } {
const userIdMatches = userId === this.streamService.currentUser.messages.id; (this point)
return {
outgoing: userIdMatches,
incoming: !userIdMatches,
};
}
}

How can I change the back button text and click action for a specific page in IONIC 2+?

I have found that many solutions are only answered in parts and though it might be useful to combine two solutions into one answer relating to the question asked above: "How can I change the back button text and click action for a specific page in IONIC 2+?"
This question was answered elsewhere but in many different parts meaning they only covered "changing the text" or showing how to perform a "custom click action" for the back button using various solutions. This answer is primarily to combine the two to showcase the most simple solution. This solution also includes the physical back button of devices like Android and Windows based phones. iPhones doesn't have a back button.
Each file will be displayed below in full to help junior developers see the fuller picture.
src/app/app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule, Navbar, NavController, AlertController } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { DashboardPage } from '../pages/dashboard/dashboard';
import { SitesPage } from '../pages/sites/sites';
import { NavigationProvider } from '../providers/navigation/navigation';
#NgModule({
declarations: [
MyApp,
HomePage,
DashboardPage,
SitesPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
DashboardPage,
SitesPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
NavigationProvider
]
})
export class AppModule {}
src/app/app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { NavigationProvider } from '../providers/navigation/navigation';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = HomePage;
constructor(private platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private navProvider: NavigationProvider) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
platform.registerBackButtonAction(() => {
this.navProvider.backButtonAction();
});
statusBar.styleDefault();
splashScreen.hide();
});
}
}
src/pages/dashboard/dashboard.ts
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController, Navbar } from 'ionic-angular';
import { SitesPage } from '../sites/sites';
import { NavigationProvider } from '../../providers/navigation/navigation';
#IonicPage()
#Component({
selector: 'page-dashboard',
templateUrl: 'dashboard.html',
})
export class DashboardPage {
#ViewChild(Navbar) navBar: Navbar;
constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public navProvider: NavigationProvider) {}
ionViewDidLoad() {
this.viewCtrl.setBackButtonText('Logout');
this.navBar.backButtonClick = () => {
this.navProvider.backButtonAction();
};
}
sites() {
this.navCtrl.push(SitesPage);
}
}
src/providers/navigation/navigation.ts
import { Injectable } from '#angular/core';
import { Platform, NavController, AlertController } from 'ionic-angular';
import { App } from "ionic-angular/index";
#Injectable()
export class NavigationProvider {
logoutAlert: any = null;
exitAppAlert: any = null;
private navCtrl: NavController;
constructor(private platform: Platform, private app: App, private alertCtrl: AlertController) {
//get the nav controller which is only ready when the platform is ready
platform.ready().then(() => {
this.navCtrl = app.getActiveNavs()[0];
});
}
//* perform the back button action
backButtonAction() {
// can we pop this page?
if(this.navCtrl.canGoBack()) {
// are we on the page that we want to trigger the logout alert?
const view = this.navCtrl.getActive();
if(view.component.name == 'DashboardPage') {
// is the logout alert still visible?
if(this.logoutAlert) {
// dismiss it instead :)
this.logoutAlert.dismiss();
this.logoutAlert = null;
} else {
// show the logout alert
this.logoutAlertAction();
}
} else {
//pop the page to perform default back action
this.navCtrl.pop();
}
} else {
// we are at the root page so the next step is to exit the app
// is the exit app alert still visible?
if(this.exitAppAlert) {
// dismiss it instead :)
this.exitAppAlert.dismiss();
this.exitAppAlert = null;
} else {
this.exitAppAlertAction();
}
}
}
//*/
//* prompt the user before logging out
logoutAlertAction() {
this.logoutAlert = this.alertCtrl.create({
title: 'Logout',
message: 'Are you sure you want to log out?',
buttons: [
{
text: 'No',
role: 'cancel',
handler: () => {
// don't do anything
}
},
{
text: 'Yes',
handler: () => {
// clear sessions or do something to log the user out before popping the page
this.navCtrl.pop();
}
}
]
});
this.logoutAlert.present();
}
//*/
//* prompt the user before exiting the application
exitAppAlertAction() {
this.exitAppAlert = this.alertCtrl.create({
title: 'Exit Application',
message: 'Are you sure you want to exit the app?',
buttons: [
{
text: 'Yes',
handler: () => {
// exit the application
this.platform.exitApp();
}
},
{
text: 'No',
role: 'cancel',
handler: () => {
// don't do anything
this.exitAppAlert = null;
}
}
]
});
this.exitAppAlert.present();
}
//*/
}

fix the navigation with navcontroller in ionic 2

i'm trying to implement a simple ionic app with login authentification, when the user enter the credentials and hit login i sat the Root for the Nav to be the TabsPage that contains the home,contact and about pages.The problem is when the i hit the logout button in the home page it redirect the home tab(see logout function in home.ts) to the login page(set the Root to loginPage) and the three tabs stays at the bottom, i want fully redirection to the loginPage any suggestions ?
login page
after logout in home page
app.component.ts :
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { LoginPage } from '../pages/login/login';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = LoginPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
login.ts :
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import {TabsPage} from '../tabs/tabs';
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
loading: Loading;
registerCredentials = { email: '', password: '' };
constructor(private nav: NavController, private auth: AuthService, private alertCtrl: AlertController, private loadingCtrl: LoadingController) { }
public login() {
//this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
console.log('allowed');
this.nav.setRoot(TabsPage); //move to tabspage
} else {
this.showError("Access Denied");
console.log('denied');
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Please wait...',
dismissOnPageChange: true
});
this.loading.present();
}
showError(text) {
//this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'Fail',
subTitle: text,
buttons: ['OK']
});
alert.present(prompt);
}
}
home.ts :
import { Component } from '#angular/core';
import { NavController, IonicPage } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import {LoginPage} from '../login/login';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
username = '';
email = '';
constructor(private nav: NavController, private auth: AuthService) {
let info = this.auth.getUserInfo();
this.username = info['name'];
this.email = info['email'];
}
public logout() {
this.auth.logout().subscribe(succ => {
this.nav.setRoot(LoginPage)
});
}
}
I got around this issue by getting the navcontroller from app.
import {App, NavController, IonicPage } from 'ionic-angular';//import App
Inject the app object.
constructor(private app:App,private nav: NavController, private auth: AuthService) {//...
}
In logout function, use getRootNav().
public logout() {
this.auth.logout().subscribe(succ => {
this.app.getRootNav().setRoot(LoginPage)
});

Ionic 2: How to call Provider function in Controller class

I have created new Cordova Plugin only on my machine. Then I added it to my project. It is working fine when I call that plugin. Now, I tried to make a structured caller for my plugin. I created a Provider for it, but the problem is I don't know how to call my plugin function from my Controller class. Below is my sample code.
Provider: my-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
declare let myPlugin: any;
#Injectable()
export class MyService {
constructor(public http: Http) {
console.log('Hello MyService Provider');
}
public myFunction() {
myPlugin.myPluginFunction(
(data) => {
return data;
},
(err) => {
return err;
});
}
}
Pages: my-page.ts
import { Component } from '#angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { MyService } from '../../providers/my-service';
#Component({
selector: 'page-my-page-ionic',
templateUrl: 'hello-ionic.html'
})
export class MyPage {
constructor(private viewCtrl: ViewController, private myService: MyService) {}
ionViewWillEnter() {
//I tried to call like this
this.myService.myFunction().subscribe(
data => {
alert("success");
},
error => {
alert("error");
});
}
}
It returns me this error - Property 'subscribe' does not exist on type 'void'. I don't know how to call that function, since my provider returns me success or error.
I think since your myFunction() does not return any observable you cannot subscribe to it. It just returns data directly.
You can use it like this in this case:
var data = this.myService.myFunction();
console.log("Data from plugin is :", data);
If you want to use it as an Observable, return a new observable like this:
public myFunction() {
return Observable.create(observer => {
myPlugin.myPluginFunction(
(data) => {
observer.next(data);
},
(err) => {
observer.next(data);
});
},
(err) => {
observer.error(err);
});
}

How to write the post method in ionic?

I am new to the ionic framework,I had written the post call, I don't know exactly the post method.When i entered the submit button in forgot password page,if the user is already registered then should display the next page else it should display the alert message.
Below is my code:
import { Component } from '#angular/core';
import { configurator } from '../../providers/configurator';
import { NavController } from 'ionic-angular';
// import { LoginPage } from '../login/login';
import { persistence } from '../persistence/persistence';
#Component({
templateUrl: 'home.html'
})
export class home {
public loginId = "";
constructor(public navCtrl: NavController) {
}
generateOTP(newstate) {
console.log("invoking generateOTP FN");
var _this = this;
this.login.generateOTP(this.loginId, function(result,data){
if(result == '1') {
alert(data);
var a = document.createElement('a');
a.href="OTP page";
}
else {
//this.showRePasswd = this.showRePasswd;
alert(data);
}
})
}
}
This is my ionic-page:enter image description here
Can anyone help me!!!
my post belowed in IONIC2
import { Http, Response } from '#angular/http';
constructor(public navCtrl: NavController, private http: Http) { }
this.http.post(`${POST_URL}/log/add`, JSON.stringify(this.currentLocation), {headers})
.toPromise()
.then((response) => {
if (response.status !== 201) {
this.trace.error('log','postLog',`error response: ${response.status}`);
}
})
.catch(error => {
this.trace.error('log','postLog',`err post log:${error}`);
});