Variable defined, but the console says not - ionic-framework

It's a simple alertController box, which create a checklist element. When I click on add, the function addCheck() of the class ChecksPage is called :
export class ChecksPage implements OnInit {
checkList: Check[] = [];
constructor(private alertCtrl: AlertController) { }
ngOnInit() {
}
addCheck(){
this.alertCtrl.create({
header: 'Nouvelle liste',
inputs:[{
name:'nom',
placeholder: 'Nom'
}],
buttons:[
{
text: 'Annuler',
role: 'cancel'
},
{
text: 'Ajouter',
handler: data => {
if(typeof data.nom !=null){
let newCheck: Check;
newCheck.id = ''+this.checkList.length;
newCheck.title = data.nom;
this.checkList.push(newCheck);
}
}
}]
}).then(alertEl => alertEl.present());
}
}
But, I have an error : the variable newCheck is undefined. Why ?
Check is an interface :
export interface Check{
id: string;
title: string;
}

You didn't init your variable, please do as follow:
const newCheck = {
id: ''+this.checkList.length,
title: data.nom
} as Check;

Related

ERROR: No card found (Card error) or ERROR: Fetching the page failed because the request timed out. Using Angular SSR and Firestore

When using https://cards-dev.twitter.com/validator to validate my meta tags for my page on my site that's using dynamically retrieved data from Firestore, it keeps flagging ERROR: No card found (Card error) or ERROR: Fetching the page failed because the request timed out.. But, it has no issues with static data tho.
Angular CLI: 13.2.3
Node: 16.14.0
Firebase: 9.6.6
nguniversal/express-engine: 13.0.2
angular/fire: 7.2.1
seo.service.ts
import { Inject, Injectable } from '#angular/core';
import { Meta, MetaDefinition, Title } from '#angular/platform-browser';
import { ActivatedRoute, Router } from '#angular/router';
import { MetaDataModel } from '../../shared/models/meta-data';
const defaultMetadata: MetaDataModel = {
title:
'Some title....',
imgURL:
'https://firebasestorage.googleapis.com/v0...',
description:
'Some description...',
keywords: ['Angular', 'meta tags', 'Angular Universal'],
type: 'website',
};
#Injectable({
providedIn: 'root',
})
export class SeoService {
/* ❗️❗️📌TODO: CHANGE TO https://rivervalleyirregulars.com */
url = 'https://river-valley-irregulars-dev.web.app';
constructor(
private metaTagService: Meta,
private titleService: Title,
private router: Router
) {}
updateTitle(title: string) {
this.titleService.setTitle(`RVI: ${title}`);
}
updateMetaTags(
metadata: Partial<MetaDataModel>,
index: boolean = true
): void {
const tags = [
{ property: 'og:url', content: `${this.url}${this.router.url}` },
{ name: 'robots', content: index ? 'index, follow' : 'noindex' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ name: 'title', content: metadata.title },
{ property: 'og:title', content: metadata.title },
{ name: 'description', content: metadata.description },
{ property: 'og:description', content: metadata.description },
{ name: 'image', content: metadata.imgURL },
{ property: 'og:image', content: metadata.imgURL },
{ name: 'keywords', content: metadata.keywords?.join(', ') },
{ property: 'og:type', content: metadata.type },
// TWITTER CARD
{ name: 'twitter:card', content: 'summary' },
{ name: 'twitter:image', content: metadata.imgURL },
{ name: 'twitter:title', content: metadata.title },
{ name: 'twitter:site', content: '#rvi' },
{ name: 'twitter:creator', content: '#rvi' },
{ name: 'twitter:description', content: metadata.description },
];
tags.forEach((meta: any) => {
this.metaTagService.updateTag(meta);
});
}
}
home.component.ts
export class HomeComponent implements OnInit {
constructor(#Optional() private seo: SeoService) {}
ngOnInit(): void {
if (this.seo) {
this.seo.updateMetaTags({
title:
'Some title...',
imgURL:
'https://firebasestorage.googleapis.com/v0....',
description:
'Some descriptions....',
keywords: ['Angular', 'meta tags', 'Angular Universal'],
type: 'website',
});
}
loadTypeWriter();
}
}
data.component.ts
export class DataComponent {
data$?: Observable<any>;
constructor(
#Optional() private seo: SeoService,
private route: ActivatedRoute,
private firestore: Firestore,
private router: Router
) {}
ngOnInit() {
this.route.paramMap.subscribe((params: ParamMap) => {
const id = params.get('id');
const productRef = doc(this.firestore, `data/${id}`);
this.data$ = docData(productRef, { idField: 'id' }).pipe(
traceUntilFirst('firestore')
);
/* UPDATE META TAGS */
this.data$.subscribe((data) => {
if (this.seo) {
this.seo.updateMetaTags({
title: `RVI: ${data.organization} - ${data.title}`,
description: data.description,
imgURL: data.img_url,
});
}
});
});
}
}

Navigate to specific tab in Ionic 3

I'm having trouble selecting the index of Tabs when on Button click. I'm calling the index like so, in android-tutorial.ts but it isn't working.
I am calling the function in android-tutorial.ts, with the function startApp();
Is there any other way to do this? What am I doing wrong?
Hope you can help me!
tabs-page.ts
mySelectedIndex: number = 0;
tabs: Tab[] = [
{
page: "NoveltiesPage",
icon: "icon-novelties"
},
{
page: "BrandsPage",
icon: "icon-menus"
},
{
page: "LoginPage",
icon: "icon-user"
},
{
page: "StoresPage",
icon: "icon-stores"
},
{
page: "AboutPage",
icon: "custom-hat"
}
];
constructor(public navCtrl: NavController, public events: Events, public alertCtrl: AlertController, public storageProvider: StorageProvider, public pushProvider: PushProvider, public aboutProvider: AboutProvider, private appVersion: AppVersion, public platform: Platform, public deviceProvider: DeviceProvider, public alertProvider: AlertProvider) {
this.platform.ready().then(() => {
this.getVersion();
//Navigate to Login Page on Startup
this.storageProvider.getUser().then((user: User) => {
if (user && user.token) {
let token = user.token;
this.events.publish("user:login", token);
this.pushProvider.start();
}
});
});
this.platform.resume.subscribe(() => {
this.getVersion();
});
this.events.subscribe("user:login", () => {
this.tabs[2].page = "AccountPage";
});
this.events.subscribe("user:logout", () => {
this.tabs[2].page = "LoginPage";
});
this.events.subscribe("user:notification", (data: any) => {
switch (data.additionalData.type) {
case "novelty":
this.events.publish("novelty:new");
this.navCtrl.push("NoveltyPage", {
id: data.additionalData.id
});
break;
// case "message":
// this.events.publish('message:new');
// this.navCtrl.push('MessagePage', {
// id: data.additionalData.id,
// });
// break;
default:
this.events.publish("card:update");
this.alertProvider.show(data.title, data.message);
break;
}
});
}
getVersion() {
//get the version of the method
this.aboutProvider.app().subscribe((data: any) => {
this.curVersion = data.data;
//get platform of the Device
let platform = this.deviceProvider.getPlatform();
let curV: string = this.curVersion.ios;
let store: string = this.curVersion.app_ios_url;
if (platform == "Android") {
curV = this.curVersion.android;
store = this.curVersion.app_android_url;
}
//get the version of the app
this.appVersion
.getVersionNumber()
.then((data: any) => {
let version = data;
if (curV > version) {
switch (this.curVersion.status) {
case "1":
this.alertProvider.action(this.curVersion.title, this.curVersion.message, [{ text: "Cancelar" }, { text: "Atualizar", action: "link", link: store }]);
break;
case "2":
this.alertProvider.action(this.curVersion.title, this.curVersion.message, [{ text: "Atualizar", action: "link", link: store }], false);
break;
default:
break;
}
}
})
.catch(e => {});
});
}
}
android-tutorial.ts
import { Component, ViewChild } from '#angular/core';
import { Storage } from '#ionic/storage';
import { IonicPage, Slides, NavController, Events, NavParams } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-android-tutorial',
templateUrl: 'android-tutorial.html',
})
export class AndroidTutorialPage {
seen: boolean;
currentIndex: number = 1;
#ViewChild('slides') slides: Slides;
constructor(public navCtrl: NavController, public navParams: NavParams, public storage: Storage, public events: Events) {
this.seen = this.navParams.data.seen;
if (!this.seen) {
this.seen = false;
}
}
startApp() {
this.navCtrl.setRoot('TabsPage', {
mySelectedIndex : 2
});
this.storage.set('hasSeenTutorial', 'true');
}
back() {
this.navCtrl.pop();
}
slideChanged() {
let index = this.slides.getActiveIndex();
if(index != 4) {
this.currentIndex = this.slides.getActiveIndex() + 1;
}
}
}
tabs-page.html
<ion-tabs [selectedIndex]="mySelectedIndex">
<ion-tab [root]="tab.page" tabIcon="{{tab.icon}}" *ngFor="let tab of tabs"></ion-tab>
</ion-tabs>
Ok I find a way to do it.
Here's how i solved it. I needed to be able to pass an Index to the tabs-page.ts from android-tutorial.ts
Here's the only thing I added:
constructor(public navCtrl: NavController, public events: Events, public alertCtrl: AlertController, public storageProvider: StorageProvider, public pushProvider: PushProvider, public aboutProvider: AboutProvider, private appVersion: AppVersion, public platform: Platform, public deviceProvider: DeviceProvider, public alertProvider: AlertProvider, public params: NavParams) {
this.mySelectedIndex = this.params.get('mySelectedIndex'); <---- THIS IS THE LINE I ADDED
this.platform.ready().then(() => {
this.getVersion();
//Navigate to Login Page on Startup
this.storageProvider.getUser().then((user: User) => {
if (user && user.token) {
let token = user.token;
this.events.publish("user:login", token);
this.pushProvider.start();
}
});
});
this.platform.resume.subscribe(() => {
this.getVersion();
});
this.events.subscribe("user:login", () => {
this.tabs[2].page = "AccountPage";
});
this.events.subscribe("user:logout", () => {
this.tabs[2].page = "LoginPage";
});
this.events.subscribe("user:notification", (data: any) => {
switch (data.additionalData.type) {
case "novelty":
this.events.publish("novelty:new");
this.navCtrl.push("NoveltyPage", {
id: data.additionalData.id
});
break;
// case "message":
// this.events.publish('message:new');
// this.navCtrl.push('MessagePage', {
// id: data.additionalData.id,
// });
// break;
default:
this.events.publish("card:update");
this.alertProvider.show(data.title, data.message);
break;
}
});
}

Ionic 4 Manual Override of ion-select

Hi I need 'select from list' functionality on a form but with the ability to enter a value manually if needed.  I've been trying ion-select but there doesn't seem to be a way to have a manual override.  Is there a way to do this?
Thanks
For example
<ion-header>
<ion-toolbar>
<ion-title>kitlist testy</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<form [formGroup]="myForm">
<ion-list>
<ion-item>
<ion-label stacked>Lens</ion-label>
<ion-select placeholder="Select One">
<ion-select-option value="f">Female</ion-select-option>
<ion-select-option value="m">Male</ion-select-option>
</ion-select>
<ion-input type="text" formControlName='lens'></ion-input>
</ion-item>
</ion-list>
</form>
</ion-content>
will give
I want the user to be able to add their own value - which I will then store.
Thanks
Following Sergey's very helpful answer I have tried getting this to work and I'm stuck at inputAlert.onDidDismiss which gives me
Expected 0 arguments, but got 1
Here's the code which I have adjusted for my use case:-
import { Component, OnInit } from "#angular/core";
import { FormBuilder, FormGroup } from "#angular/forms";
import { AlertController } from "#ionic/angular";
#Component({
selector: "app-kitlist",
templateUrl: "./kitlist.page.html",
styleUrls: ["./kitlist.page.scss"]
})
export class KitlistPage implements OnInit {
kitlist = ["lens1", "lens2", "Custom"];
currentLens: any;
myForm: FormGroup;
constructor(
private fb: FormBuilder,
private alertController: AlertController
) {
this.myForm = new FormGroup({});
}
ngOnInit() {
this.myForm = this.fb.group({
lens: ""
});
this.myForm.valueChanges.subscribe(console.log);
}
submitForm() {
console.log("submit");
}
selectChanged(selectedLens) {
if (selectedLens === "Custom") {
this.inputCustomLensValue();
} else {
this.currentLens = selectedLens;
}
}
async inputCustomLensValue() {
const inputAlert = await this.alertController.create({
header: "Enter your custom lens:",
inputs: [{ type: "text", placeholder: "type in" }],
buttons: [{ text: "Cancel" }, { text: "Ok" }]
});
inputAlert.onDidDismiss(data => {
let customLensName: string = data.data.values[0];
if (customLensName) {
let indexFound = this.kitlist.findIndex(
lens => lens === customLensName
);
if (indexFound === -1) {
this.kitlist.push(customLensName);
this.currentLens = customLensName;
} else {
this.currentLens = this.kit[indexFound];
}
}
});
await inputAlert.present();
}
}
Since ion-select under the hood uses alert controller, I would leverage it directly and I would have a couple of alerts working together here:
In your template:
<ion-item>
<ion-label>Hair Color</ion-label>
<ion-button slot="end" (click)="selectColors()">{{ currentOptionLabel }}
<ion-icon slot="end" name="arrow-dropdown"></ion-icon>
</ion-button>
</ion-item>
You can style ion-button according to your needs.
Now in your ts file we can import Alert Controller and have 2 of them: one for selecting premade options and one that we will create input type of alert in case our user wants to add custom value.
I am not using button's handler's methods here to make sure Angular can pick up all the data changes:
import { Component } from '#angular/core';
import { AlertController } from '#ionic/angular';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.css'],
})
export class HomePage {
public colorOptions: Array<{type: string, label: string, value: string}>
public currentColorOptionIndex: number;
public currentOptionLabel: string;
constructor(public alertController: AlertController) {
this.currentColorOptionIndex = 1;
this.colorOptions = [
{
type: "radio",
label: "Custom",
value: "Custom"
},
{
type: "radio",
label: "Brown",
value: "Brown",
},
{
type: "radio",
label: "Dark",
value: "Dark",
}
]
this.currentOptionLabel = this.colorOptions[this.currentColorOptionIndex].label;
}
async selectColors() {
const radioAlert = await this.alertController.create({
header: 'Prompt!',
inputs: this.colorOptions as any,
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary'
}, {
text: 'Ok'
}
]
});
await radioAlert.present();
radioAlert.onDidDismiss().then((data) => {
let selectedValue = data.data.values;
if (selectedValue === 'Custom') {
this.inputCustomColorValue()
};
this.currentColorOptionIndex = this.colorOptions.findIndex(option => option.value == selectedValue)
this.currentOptionLabel = this.colorOptions[this.currentColorOptionIndex].label;
})
}
async inputCustomColorValue() {
const inputAlert = await this.alertController.create({
header: 'Enter your custom color:',
inputs: [
{
type: 'text',
placeholder: 'type in'
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary'
}, {
text: 'Ok',
}
]
});
await inputAlert.present();
inputAlert.onDidDismiss().then((data) => {
let customValue = data.data.values[0];
let indexFound = this.colorOptions.findIndex(option => option.value == customValue)
if (indexFound !== -1) {
this.currentColorOptionIndex = indexFound
} else {
this.colorOptions.push(
{
type: 'radio',
label: customValue,
value: customValue,
}
)
this.currentColorOptionIndex = this.colorOptions.length - 1;
};
this.currentOptionLabel = this.colorOptions[this.currentColorOptionIndex].label;
})
}
}
Updated: added the fact that now in latest Ionic versions (compared to Stackblitz that uses old 4 beta) onDidDismiss hook returns Promise and requires onDidDismiss.then((data) => {}) syntax vs onDidDismiss((data => {})

ionicV3 back button navigation problem showing nav.getActive is not a function

I am trying to overwrite the navigation back button to my needs in android using ionic 3 but whenever i run my app it shows an error when i press back navigation button saying "nav.getActive is not a function" due to this back button doesn't work.
Updated Code is as followed
export class MyApp {
rootPage:any = LoginPage;
public counter=0;
#ViewChild(Nav) nav: Nav;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,public globalProvider: GlobalProvider,
public googlePlus: GooglePlus, public zone: NgZone, private readonly firebase: Firebase, private alertCtrl: AlertController,
public toastCtrl: ToastController, public app: App) {
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();
platform.registerBackButtonAction(() => {
const activeView = this.nav.getActive().name // This will give you the activeview name
if(activeView === 'HomePage') {
if (this.nav.canGoBack()){ //Can we go back?
this.nav.pop();
} else {
const alert = this.alertCtrl.create({
title: 'App termination',
message: 'Do you want to close the app?',
buttons: [{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Application exit prevented!');
}
},{
text: 'Close App',
handler: () => {
platform.exitApp(); // Close this application
}
}]
});
alert.present();
}
}
this.nav.push(TabsPage);
}, 1);
this.firebase.onNotificationOpen().subscribe(notification => {
console.log('notification info: ', notification);
/*!notification.tap
? console.log('The user was using the app when the notification arrived...')
: console.log('The app was closed when the notification arrived...');
let notificationAlert = this.alertCtrl.create({
title: notification.title,
message: notification.body,
buttons: ['Ok']
});
notificationAlert.present();*/
},
error => {
console.error('Error getting the notification', error);
});
});
/*platform.registerBackButtonAction(() => {
if (this.counter == 0) {
this.counter++;
this.presentToast();
setTimeout(() => { this.counter = 0 }, 3000)
} else {
// console.log("exitapp");
platform.exitApp();
}
}, 0) });*/
}
Try like this.
#ViewChild(Nav) nav: Nav;
constructor(platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public globalProvider: GlobalProvider,
public toastCtrl: ToastController,
public googlePlus: GooglePlus,
public zone: NgZone,
public app: App,
public alertCtrl: AlertController
) {
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();
platform.registerBackButtonAction(() => {
**const activeView = this.nav.getActive().name** // This will give you the activeview name
if(active.instance instanceof HomePage) {
if (nav.canGoBack()){ //Can we go back?
nav.pop();
} else {
const alert = this.alertCtrl.create({
title: 'App termination',
message: 'Do you want to close the app?',
buttons: [{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Application exit prevented!');
}
},{
text: 'Close App',
handler: () => {
platform.exitApp(); // Close this application
}
}]
});
alert.present();
}
}
nav.push(HomePage);
}, 100);
});
}

Loader Appearing continue in ionic ios when login

I am new to ionic development and I am facing some issue
We are consuming an API in the ionic3 app.
When the user enters the credentials for login whether they are valid or invalid it shows the message according to the results from API in android.
But When i enter the wrong credentials in the ios build it will continue shows the loader and not giving the API result.
Following the app.component
import { Component, ViewChild } from '#angular/core';
import { Platform, Events, Nav, AlertController } from 'ionic-angular';
//import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { MenuController } from 'ionic-angular/components/app/menu-controller';
import { StorageService } from '../pages/shared/storage.service';
import { ToastService } from '../pages/shared/toast.service';
import { Network } from '#ionic-native/network';
//import { Observable } from 'rxjs/Observable';
import { UserService } from '../pages/shared/user.service';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav;
alert: any;
isAlertShown: boolean;
task: any;
rootPage: any = '';
userDetails: any;
showSubmenu: boolean = true; //for open always
constructor(public platform: Platform, public splashScreen: SplashScreen,
public menu: MenuController,
private storage: StorageService, private toast: ToastService, public events: Events,
private push: Push,
private alertCtrl: AlertController, public network: Network, private api: UserService) {
platform.ready().then(() => {
this.userDetails = this.storage.getData('userDetails');
this.isAlertShown = false;
this.task = setInterval(() => {
this.checkInternet();
}, 3000);
this.pushSetup();
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
} else {
this.rootPage = 'login';
}
this.initializeApp();
});
events.subscribe('user:login', (username) => {
// user and time are the same arguments passed in `events.publish(user, time)`
this.getLoggedIn();
});
events.subscribe('user:logout', () => {
this.rootPage = 'login';
});
events.subscribe('root:change', (page) => {
// user and time are the same arguments passed in `events.publish(user, time)`
this.rootPage = page;
});
events.subscribe('user:pic', (userpic) => {
// user and time are the same arguments passed in `events.publish(user, time)`
this.userDetails = this.storage.getData('userDetails');
this.userDetails = {
userId: this.userDetails.userId,
username: this.userDetails.username,
profileUrl: userpic
}
this.storage.saveData('userDetails', this.userDetails);
this.getLoggedPic('pic');
});
}
initializeApp() { //for reduce time of white screen after splash
this.platform.ready().then(() => {
// do whatever you need to do here.
setTimeout(() => {
this.splashScreen.hide();
}, 100);
});
}
checkInternet() {
this.alert = this.alertCtrl.create({
title: 'Disconnected',
message: 'Please connect your device to internet',
buttons: [
{
text: 'Try again',
handler: () => {
this.checkagain();
}
}
], enableBackdropDismiss: false
});
this.api.getCategoryList()
.then(result => {
// console.clear();
if (result.type == 'error') {
if (this.isAlertShown == false) {
this.alert.present();
this.isAlertShown = true;
}
this.storage.saveData('connect', 'offline');
}
else if (result.status == true) {
this.storage.saveData('connect', 'online');
this.alert.dismiss();
}
})
}
public checkagain() {
this.isAlertShown = false;
//this.alert.dismiss();
}
public logout(): void {
this.storage.removeData('userDetails');
this.toast.ShowNotification('Logout Successful', 'bottom');
this.rootPage = 'login';
}
getLoggedPic(page) {
this.userDetails = this.storage.getData('userDetails');
if (page == "pic") {
this.userDetails.profileUrl = this.userDetails.profileUrl + "?" + new Date().getTime();
}
}
getLoggedIn() {
this.userDetails = this.storage.getData('userDetails');
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
this.userDetails = this.storage.getData('userDetails');
this.userDetails.profileUrl = this.userDetails.profileUrl + "?" + new Date().getTime();
} else {
this.rootPage = 'login';
}
}
openMenu(): void {
//Commented for click on edit profile to not collepes
//this.showSubmenu = !this.showSubmenu;
}
openPage(pagename: string) {
this.rootPage = pagename;
//this.nav.push(pagename);
}
openHomePage(pagename: string) {
this.rootPage = pagename;
}
pushSetup() {
console.log("inside pushSetup");
const options: PushOptions = {
android: {
senderID: 'xxxxxxxxxxx
forceShow: 'true'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
pushObject.on('registration').subscribe((registration: any) => this.storage.saveData("token", registration.registrationId));
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
}
Following is my login.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, Events, LoadingController } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { UserLogin } from '../shared/user';
import { UserService } from '../shared/user.service';
import { ToastService } from '../shared/toast.service';
import { StorageService } from '../shared/storage.service';
import { MenuController } from 'ionic-angular/components/app/menu-controller';
import { Platform } from 'ionic-angular';
#IonicPage({
name: 'login'
})
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
public loginForm: FormGroup;
public submitted: boolean = false;
public userDetails: any;
private isUserLoggin: boolean = false;
private devicetype: any;
unamePattern = "(?:\d{10}|\w+#\w+\.\w{2,3})";
constructor(public nav: NavController, public formBuilder: FormBuilder,public platform: Platform,
private userService: UserService, private toast: ToastService, public loading: LoadingController, private storage: StorageService, private menuCtrl: MenuController,
public events: Events) {
if (this.platform.is('ios')) {
this.devicetype = "ios";
}
else {
this.devicetype = "android";
}
this.menuCtrl.enable(false); // for sidemenu disable
this.nav = nav;
this.isUserLoggin = this.userService.isUserLoggedIn();
this.loginForm = formBuilder.group({
username: ['', Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
}
// get username() {
// return this.loginForm.get('username');
// }
public save(model: UserLogin, isValid: boolean) {
this.submitted = true;
if (isValid) {
const formData = new FormData();
debugger
formData.append("user_login", model.username);
formData.append("user_password", model.password);
formData.append("device_type",this.devicetype);
formData.append("device_id",""+this.storage.getData("token"));
// console.log("storage id of device ="+this.storage.getData("token"));
let loader = this.loading.create({
content: 'Please wait'
});
loader.present().then(() => {
});
//this.toast.ShowLoaderOnLoad();
try {
this.userService.loginUser(formData)
.then(result => {
loader.dismiss();
if (result.status === true) {
this.userDetails = {
userId: result.data.user_id,
username: result.data.first_name,
profileUrl: result.data.picture_url
}
this.storage.saveData('userDetails', this.userDetails);
this.events.publish('user:login', result.data.first_name); //send an event to menu for show name
this.toast.ShowNotification(result.message, 'bottom');
this.nav.setRoot('welcome');
}
else if (result.status === false) {
this.loginForm = this.formBuilder.group({
username: [model.username, Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
this.submitted = false;
this.toast.ShowNotification(result.message, 'bottom');
}
else {
this.toast.ShowNotification('Something went wrong!', 'bottom');
this.loginForm.reset();
this.submitted = false;
isValid = false;
}
})
}
catch (error) {
this.loginForm = this.formBuilder.group({
username: [model.username, Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
this.submitted = false;
this.toast.ShowNotification('Something went wrong!', 'bottom');
}
}
}
ionViewWillEnter() {
if (this.isUserLoggin) {
this.nav.setRoot('welcome');
}
}
public gotoregister() {
this.nav.setRoot('register');
}
public gotoforget() {
this.nav.setRoot('forget');
}
public resetForm() {
this.submitted = false;
}
}
your
loader.present().then(() => {
});
is empty. Which means that your loader.dismiss() might activate before it is instantiated.
Try to put your try block in the call back of the present() function:
try {
etc...}
please Try with this
this.userService.loginUser(formData)
.then((res:any)=>{
//Success Code here
//Stop Loader
}).catch((err:any)=>{
//Error handling and Stop loader
})