Struggling to retrieve variable within the .catch function in Ionic 3

I am having trouble accessing the toast variable from the constructor in order to toast errors. It keeps showing as undefined, and I'm not sure why. This issue seems to only occur in this class, which is strange. The error message reads "ERROR TypeError: Cannot read property 'toastCtrl' of undefined". Any assistance would be greatly appreciated.

//Imports

import {
    Component,
    ChangeDetectorRef
} from '@angular/core';
import {
    NavController,
    NavParams,
    Platform,
    ToastController
} from 'ionic-angular';


import {
    Keyboard
} from '@ionic-native/keyboard';

import {
    Storage
} from '@ionic/storage';
import {
    fireUser
} from './../../objects/firebaseStructures';

import {
    MySegService
} from './../../services/myseg-api.service';



//Component

@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
})

export class LoginPage {

    // Login details
    email: string;
    emailTest: string;
    loggedUser: fireUser;
    password: string;
    passwordTest: string;
    responseMessage: string;
    success: boolean = false;
    uid: string;
    user: string;
    registerUserPage = RegisterUserPage;
    forgetpass = ForgetPasswordPage;

    constructor(public navCtrl: NavController, public navParams: NavParams, public mysegService: MySegService, private platform: Platform,
        private keyboard: Keyboard, private storage: Storage, private toastCtrl: ToastController) {

        this.loggedUser = new fireUser(null, null, null, null, null, null, null, null, null, null, null, null, null, null); //user initialization
    }

    signInUser() {
        var user2: string;
        this.mysegService.loginUser(this.email, this.password).then(res => {
                console.log(res);
            })
            .catch(function (error) {
                // Handle Errors here.
                //unsuccessful log in
                var errorCode = error.code;
                var errorMessage = error.message;
                if (errorCode === 'auth/wrong-password') {
                    let toast = this.toastCtrl.create({
                        message: 'wrong password',
                        duration: 3000,
                        position: 'top'
                    });

                    toast.onDidDismiss(() => {
                        console.log('Dismissed toast');
                    });

                    toast.present();
                } else {
                    // alert(errorMessage);
                }
                console.log(error);
            });

    }

}

Answer №1

Opt for arrow function syntax => in place of a standard function callback.

Your revised code snippet should appear as follows -

loginUser() {
        var user2: string;
        this.mysegService.loginUser(this.email, this.password).then(res => {
                console.log(res);
            })
            .catch((error) => {
                .......
            });

    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I turn off the draggable feature for a specific element in react-beautiful-dnd?

Currently, I am implementing a drag and drop functionality using TypeScript with react-beautiful-dnd. The goal is to allow users to move items between two containers - one containing user names and the other labeled "Unassigned". Here is a snapshot of the ...

Confirm that the user has interacted with every input

When it comes to validating a form, you have the ability to determine if a user has interacted with an input field or checkbox (using X.touched). Is there a built-in validator that requires a user to specifically interact with each input field at least onc ...

Leveraging Angular 8 for Multi-Tenancy Implementation

Currently, I am involved in a project that caters to multiple clients. Utilizing angular themes allows me to customize the background color, font, and other elements for each client. Additionally, I need to repurpose components by adjusting the text in var ...

Retrieve a specific category within a method and then output the entire entity post adjustments

I need to sanitize the email in my user object before pushing it to my sqlite database. This is necessary during both user creation and updates. Here's what I have so far: export const addUser = (user: CreateUser) => { db.prepare(sqlInsertUser).r ...

The user keeps finding themselves redirected back to the Home page rather than the page they are trying

Within my Angular application, users are authenticated through an OIDC provider using the library angular-auth-oidc-client. In the scenario where a user is not authenticated or their session has expired and they attempt to access a page such as https://loc ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

Using Angular 2+ to make an http-get request with parameters

I am looking to create a GET method with multiple parameters. Currently, my example works with one parameter but I need to add another. In the backend code segment below, you can see where I am trying to pass the second parameter, 'created_by', b ...

Is it possible for Angular components to retrieve information on the current route and parameters?

I am struggling to understand why it's so difficult... why we are not supposed to care about the route from outside the routed component.... HOWEVER: I am attempting to develop a service so that my header (and any other component) can have access to ...

Utilize style as a module in Angular

The issue at hand: Let's take a look at this project structure: /src /public /styles /general /tables.scss /secure /components /someTable1 /someTable.component.ts /someTable.component.css /someTa ...

A guide on utilizing ngx-translate to convert validation messages in Ionic4

In my ionic4 application, I am configuring it to support two languages - ar and en using ngx-translate library. I have two JSON files, en.json and ar.json, with the following structure: { "LOGIN": { "login": "Login", "emailOrPhone":"EMAIL OR PHO ...

The TypeScript variable is automatically assigned the type 'any' since it does not contain a specified type annotation

Issue: The variable 'environment' is implicitly assigned the type 'any' because it lacks a specific type annotation and is referenced within its own initialization code. Code Snippet: export const environment = { production: fals ...

Issue: The inject() function can only be executed within an injection context

Even after following the most recommended solutions online, I am still facing an issue that says Error: inject() must be called from an injection context. In addition to this error, I am also receiving multiple warnings such as: Warning: ###/src/ap ...

Is Angular 10 disregarding set-cookie response headers?

After logging in, I attempted to utilize a session auth cookie without success. To troubleshoot, I implemented a basic "CookieTest" method on my Dotnet Core server: [Route("CookieTest")] public ActionResult CookieTest() { var options = new CookieOptions ...

Oops! The program encountered an error where it cannot assign a value to the 'id' property of an undefined object while trying to store a session in redis

I am currently working on an Angular4 login application and I am looking to store sessions in Redis. To accomplish this, I am utilizing Express session. However, I have encountered the following error: req.session.id = userName; ...

Struggling to configure Connected React Router correctly

As I work on updating my React, Redux, and Router versions to incorporate connected-react-router, I've encountered an issue with the root reducer and store creation process. The previous functioning reducer code looked like this: const appReducer = ...

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

Ensuring type safety at runtime in TypeScript

While delving into the concept of type safety in Typescript, I encountered an interesting scenario involving the following function: function test(x: number){ console.log(typeof x); } When calling this method as test('1'), a compile time er ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

How to show an item using ngFor in Angular 5 with a delay

Currently, I am facing a situation wherein I have an array that gets filled at runtime. My goal is to display its elements in an HTML template using the ngFor loop with a slight delay between each item. For example, I want the first item to be displayed, t ...