Ionic toast message cannot read property 'create' of undefined - android

I'm trying to create a toast message when the user logins fails but the toast message is giving me an error on the create property. I'm using firebase authentication.
Cannot read property 'create' of undefined
login.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { User } from "../../models/user";
import { AngularFireAuth } from 'angularfire2/auth';
/**
* Generated class for the LoginPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
user = {} as User
constructor(private afAuth: AngularFireAuth,
public navCtrl: NavController, public navParams: NavParams) {
}
async login(user:User){
this.afAuth.auth.signInWithEmailAndPassword(user.email,user.password)
.then(res => {
this.navCtrl.setRoot('TabsPage');
}, err => {
switch (err.code) {
case "auth/wrong-password":
this.toast.create({
message: `Wrong Password`,
duration: 3000
}).present();
break;
}
});
}
}

You need to initialise the ToastController in your constructor and reference it.
In example:
constructor(
private afAuth: AngularFireAuth,
public navCtrl: NavController,
public navParams: NavParams,
public toastCtrl: ToastController /* This bit */
) {}
And then...
let toast = this.toastCtrl.create({
message: 'Wrong password, holmes.',
duration: 3000,
position: 'top'
});
toast.present();

Related

Ionic 5 Capacitor hardware back button ending the app

I have a problem testing my ionic app on my phone and android studio, when i press the hardware back button the application inmediatly exits, i've tried many solutions, but it simply won't work and won't listen to whatever i code into it.
Here is my attempt
import { Component, Renderer2, ViewChild } from '#angular/core';
import { IonRouterOutlet, Platform } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { TranslateService } from '#ngx-translate/core';
import { Location } from '#angular/common';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
#ViewChild(IonRouterOutlet, {static: true}) routerOutlet: IonRouterOutlet
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private renderer: Renderer2,
private translate: TranslateService,
private location: Location
) {
this.initializeApp();
}
initializeApp() {
this.translate.setDefaultLang( localStorage.getItem('default-language') ? localStorage.getItem('default-language') : navigator.language.slice(0, 2) )
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.backButtonEvent();
if (localStorage.getItem('color-theme')) {
this.renderer.setAttribute(document.body, 'color-theme', localStorage.getItem('color-theme'))
} else {
if(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches === true)
this.renderer.setAttribute(document.body, 'color-theme', 'light')
else
this.renderer.setAttribute(document.body, 'color-theme', 'dark')
}
});
}
backButtonEvent() {
this.platform.backButton.subscribeWithPriority(0, async () => {
if(!this.routerOutlet.canGoBack())
navigator["app"].exitApp()
else
this.location.back()
});
}
}
Try it this way using the #capacitor/app package:
import { App } from '#capacitor/app';
App.addListener('backButton', ({ canGoBack }) => {
if(canGoBack){
window.history.back();
} else {
App.exitApp();
}
});

How to conditionally set root page in ionic 4?

I'm working on ionic 4 application. when the user signs In, I added a checkbox to asks for Remember me, so the next time the user open the app it doesn't show the login page and directly forward the user to Home page. I have google and found this. However, while using the accepted solution, I encountered an issue, which it shows the login page for 2 or 3 seconds, then open the Home page. How I can safely achieve it without delay?
app.component.ts
import { SmsVerificationService } from 'src/app/services/SMS/sms-verification.service';
import { Component } from '#angular/core';
import { Platform } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { FCM } from '#ionic-native/fcm/ngx';
import { Plugins, Capacitor } from '#capacitor/core';
import { Router } from '#angular/router';
import { Storage } from '#ionic/storage';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private fcm: FCM,
private route: Router,
private storage: Storage
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.fcm.getToken().then(token => {
console.log(' token is ', token);
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log('on token refresh ', token);
});
this.fcm.onNotification().subscribe(data => {
console.log(data);
if (data.wasTapped) {
console.log('Received in background');
// this.router.navigate([data.landing_page, data.price]);
} else {
console.log('Received in foreground');
// this.router.navigate([data.landing_page, data.price]);
}
});
this.storage.get('isLogined').then(data => {
if (data)
this.route.navigateByUrl('/main-tab');
})
this.statusBar.styleDefault();
this.splashScreen.hide();
if (Capacitor.isPluginAvailable('SplashScreen')) {
Plugins.SplashScreen.hide();
}
});
}
}
The codes that are supposed to change the page
this.storage.get('isLogined').then(data => {
if (data)
this.route.navigateByUrl('/main-tab');
})
Do you have a separate login component? If so, you can create and add a guard to your login component to navigate to your main page when Remember me was checked.

ionic native-serial returns device not found

The problem is:
I want to establish communication between my desktop and my android smart device.
I'm trying a simple step but I get "device not found" as return
this is where I base my coding:
https://ionicframework.com/docs/native/serial/
this is the code:
import { Component, OnInit } from '#angular/core'; import {
NavController } from 'ionic-angular'; import {Serial} from
'#ionic-native/serial';
#Component({ selector: 'page-home', templateUrl: 'home.html' })
export class HomePage implements OnInit { public status:string;
constructor(public navCtrl: NavController, public serial:Serial) {
}
ngOnInit(){
this.serial.requestPermission({vid:"04e8",pid:"6860",driver:"FtdiSerialDriver"})//I
already have tried to omit the request options but got the same error
.then(()=>{
this.status = "Permission requested"; //this would be the successfully result }).catch(error=>{
this.status = error.toString(); // it's returning "device not found" }); } }
there are few content about this feature on web.

Ionic httpClient response use toast

i send login data to service, after get response in login.ts toast is not difined, how to resolve this ?
i try my toast function in another function withot condition in service its work
this my function for load service login.ts:
import { Component, OnInit } from '#angular/core';
import { NavController, MenuController, PopoverController } from "ionic-angular";
import { TabsInfluencerComponent } from '../../influencer/tabs/tabs';
import { RegisterComponent } from '../register/register';
import { ResetComponent } from '../reset/reset';
import { OfferComponent } from '../../advertiser/offer/offer';
import { ngForm } from '#angular/forms';
import { AuthService } from '../../../services/auth';
import { ToastController } from 'ionic-angular';
#Component({
templateUrl: 'login.component.html',
})
export class LoginComponent implements OnInit {
constructor(
public nav:NavController,
public menu:MenuController,
public popover: PopoverController,
private AuthService : AuthService,
private toastCtrl: ToastController) {
}
responseData : any;
public isChoose: boolean = false;
public isshowP: boolean = false;
//login and get data in service
login(form: ngForm){
this.AuthService.login(form.value.email, form.value.password)
.then(function(data) {
if(data.success == true){
localStorage.setItem('userToken',data.token);
localStorage.setItem('userData',JSON.stringify(data.user));
}else{
let toast = this.toastCtrl.create({
message: data.error,
duration: 3000
});
toast.present();
}
})
.catch(function(error) {
console.log(error);
})
}
}
this my service auth.ts:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators'
#Injectable()
export class AuthService {
private loginUrl : string = 'http://localhost:8000/api/login';
data : any;
constructor(private http: HttpClient){}
//function for login
login(email : string, password :string){
const body = {email : email, password : password};
return new Promise(resolve => {
this.http.post(this.loginUrl, body)
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
register(email : string, password :string){
}
}
after run i have error like this :
TypeError: Cannot read property 'toastCtrl' of undefined
In this case it is a problem with your this reference in your login.ts.
.then(function(data) {
...
let toast = this.toastCtrl.create({
message: data.error,
duration: 3000
});
...
})
The this is referring the anonymous function in your then block, but you want to refer back to your LoginComponent class.
How to solve this?
You could use arrow functions, that are really popular right now.
.then((data) => {
...
let toast = this.toastCtrl.create({
message: data.error,
duration: 3000
});
...
})

How to add Social share to a post Ionic wordpress app

I have been trying to insert a share button for a post in my app that is able to use the default apps installed in the android phone and can not seem to find a way through.
This is how my post.ts file looks like
import { Component } from '#angular/core';
import { NavParams, NavController, AlertController } from 'ionic-angular';
.
.
import { SocialSharing } from '#ionic-native/social-sharing';
/**
* Generated class for the PostPage page.
*/
#Component({
selector: 'page-post',
templateUrl: 'post.html'
})
export class PostPage {
post: any;
user: string;
comments: Array<any> = new Array<any>();
categories: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
public alertCtrl: AlertController,
private socialSharing: SocialSharing
) {
}
ionViewWillEnter(){
this.morePagesAvailable = true;
this.post = this.navParams.get('item');
Observable.forkJoin(
this.getAuthorData(),
this.getCategories(),
this.getComments())
.subscribe(data => {
this.user = data[0].name;
this.categories = data[1];
this.comments = data[2];
});
}
getAuthorData(){
return this.wordpressService.getAuthor(this.post.author);
}
getCategories(){
return this.wordpressService.getPostCategories(this.post);
}
getComments(){
return this.wordpressService.getComments(this.post.id);
}
loadMoreComments(infiniteScroll) {
let page = (this.comments.length/10) + 1;
this.wordpressService.getComments(this.post.id, page)
.subscribe(data => {
for(let item of data){
this.comments.push(item);
}
infiniteScroll.complete();
}, err => {
console.log(err);
this.morePagesAvailable = false;
})
}
goToCategoryPosts(categoryId, categoryTitle){
this.navCtrl.push(HomePage, {
id: categoryId,
title: categoryTitle
})
}
// Social sharing function is here
sharePost() {
this.socialSharing.share("Post Excerpt", "Post Title", "Post Image URL", "Post URL")
.then(() => {
console.log("sharePost: Success");
}).catch(() => {
console.error("sharePost: failed");
});
}
}
Problem
How do insert the post title, post url post image (REST API - JSON) into this.socialSharing.share("Post Excerpt", "Post Title", "Post Image URL", "Post URL")
so that the share button can look more like this
<button ion-fab class="btn share" mini (click)="sharePost()"></button>
EDIT
I have managed to make it work using
sharePost() {
this.socialSharing.share(this.post.excerpt.rendered, this.post.title.rendered, this.post.images.large, this.post.link)
.then(() => {
console.log("sharePost: Success");
}).catch(() => {
console.error("sharePost: failed");
});
}
However when i share like using gmail, the html special characters display
e.g title shows: catering & Cleaning Services
Excerpt shows: <p>Some text[…]</p>
How do i get rid of those html characters and just show some clean text.?
Thank you
One way i removed html tag from my wordpress post was to create a pipe and i pass the excerpt through the pipe before it gets rendered to the view
Pipe.ts was like so
import { Pipe, PipeTransform } from '#angular/core';
/**
* Generated class for the RemovehtmltagsPipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/
#Pipe({
name: 'RemovehtmltagsPipe',
})
export class RemovehtmltagsPipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: string) {
if (value) {
let result = value.replace(/<\/?[^>]+>/gi, "");
return result;
}
else {
}
}
}
Then i added the pipe as export in my component's module.ts
details.module.ts was like so
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { DetailsPage } from './details';
import { RemovehtmltagsPipe } from
'../../pipes/removehtmltags/removehtmltags';
#NgModule({
declarations: [
DetailsPage,
],
imports: [
IonicPageModule.forChild(DetailsPage),
],
exports: [RemovehtmltagsPipe],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class DetailsPageModule {}
Finally used the pipe inside my html code
details.html
<ion-row class="white-bg" padding>
<ion-col>
<h1 class="title">{{article.title.rendered | RemovehtmltagsPipe}}</h1>
<p class="date">Published: {{article.modified.split('T')[0]}} {{article.modified.split('T')[1]}}</p>
</ion-col>
</ion-row>
This should get rid of any html tags in your post.Hope this helps

Categories

Resources