Making Amazon Cognito function seamlessly with angular2 and typescript

Having trouble getting Cognito’s Forgot password feature to work

Using: Angular2+Typescript+Ionic

New to this process, followed a Quickstart guide I found here

No matter what I try, keep getting errors like Cannot read property 'CognitoUser' of undefined

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { SignupPage } from '../signup/signup';
import { ConfirmPage } from '../confirm/confirm';
import { LoginPage } from '../login/login';
import {Camera, CameraOptions} from '@ionic-native/camera';
import { Cognito } from '../../providers/aws.cognito';
import { User } from '../../providers/providers';
import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@ionic-native/Media-Capture';
import {
    AuthenticationDetails,
    CognitoIdentityServiceProvider,
    CognitoUser,
    CognitoUserAttribute,
    CognitoUserPool
} from "aws-cognito-identity";
declare var AWS: any;
declare const aws_cognito_identity_pool_id;
declare const aws_cognito_region;

var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var CognitoUser = AmazonCognitoIdentity.CognitoUser;


recovery()
  {
    AWS.config.region = aws_cognito_region;
    var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
    var userData = {
        Username : ‘testuser’,
        Pool : aws_cognito_identity_pool_id
    };
    
    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    

        // call forgotPassword on cognitoUser
        cognitoUser.forgotPassword({
            onSuccess: function(result) {
                console.log('call result: ' + result);
            },
            onFailure: function(err) {
                alert(err);
            },
            inputVerificationCode() { 
                var verificationCode = prompt('Please input verification code ', '');
                var newPassword = prompt('Enter new password ', '');
                cognitoUser.confirmPassword(verificationCode, newPassword, this);
            }
        });
    
    alert("It should have worked");
  }

Answer №1

After organizing my code and importing necessary modules, I proceeded to implement it as shown below:

    import {
    CognitoIdentityServiceProvider,
    AuthenticationDetails,
    CognitoUserPool,
    CognitoUser,
    CognitoUserAttribute,
    ICognitoUserAttributeData,
    ISignUpResult,
    CognitoUserSession,
  } from 'amazon-cognito-identity-js';

  import * as AWS from 'aws-sdk';

I then utilized these modules in my functions like so:

          const userPool = this._getUserPoolData();

          const user = new CognitoUser({ Username: usrLoginDetails.username, Pool: userPool });
          const authenticationData = { Username: usrLoginDetails.username, Password: usrLoginDetails.password };
          const authenticationDetails = new AuthenticationDetails(authenticationData);

            user.authenticateUser(authenticationDetails, {
              onSuccess: result => {
               //success here 
              },
              onFailure: error => {}, //error here,
              newPasswordRequired: () => {},  // no-op
              mfaRequired: () => {},  // no-op
              customChallenge: () => {} // no-op
            });

Upon testing, the implementation ran smoothly without encountering any issues. Feel free to reach out if you encounter any difficulties with this approach!

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

What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons <md-tab-group> <md-tab label="Tab 1">Content 1</md-tab> <md-tab label="Tab 2">Content 2</md-tab> </md-tab-group> <button md-button (click)="showTab1()">Show Tab 1< ...

Develop a dynamic component using ComponentFactoryResolver that implements a dynamic template

I am looking to create a unique dynamic component with a custom template that resolves interpolations based on the dynamic component's context. To achieve this, I understand that I can utilize the following code snippet to generate a dynamic componen ...

What is the recommended way to retrieve the Nuxt `$config` within Vuex state? Can it only be accessed through store action methods?

After using the dotenv library for my .env file, I had to change the runtimeConfig in order to secure my project's secret key. In my most recent project, I utilized nuxt version "^2.14" in SPA mode, so I only utilized "publicRuntimeConfig" in my nuxt ...

Leveraging Multiple @Input Decorators in Ionic 3 and Angular 2

Within my Ionic 3 project, I have developed a custom component called my-component. Utilizing the angular @Input functionality, data can be passed to this component with ease. In this case, I have two inputs defined as: @Input('finder') myFinder ...

Can someone assist me in configuring the mobile display for an Angular website?

I'm currently working on a website and I'm in need of some assistance to fix the mobile view. The main issue I'm facing is with the menu which contains 5 buttons. While I'm happy with how it looks on a laptop or desktop, the mobile view ...

Effortless column organization with Bootstrap

My goal is to simplify my column arrangement based on a boolean value. If the value is false <div class="row"> <div class="col-4">A</div> <div class="col-4">B</div> ...

When the React Native Expo app is running, the TextInput form is covered by the keyboard

When I launch the app using expo and implement my DateFormInput component, the issue of Keyboard covering TextInput arises. Despite trying packages like "@pietile-native-kit/keyboard-aware-scrollview", "@types/react-native-keyboard-spacer", "react-native-k ...

Having difficulty handling the "of" class within the "rxjs" framework

I have created a custom class named ValueService. Here is the code snippet: import { Injectable } from '@angular/core'; import { of } from 'rxjs'; import { delay } from 'rxjs/operators'; @Injectable() export class ValueSer ...

What is the best way to showcase several items in a slide with Ionic 2?

I am a beginner with Ionic 2 and I am trying to display multiple products in a single slide. While I have successfully displayed the slide, I am seeing small dots below the image. How can I remove these dots? Below is my HTML code: <ion-row class="bran ...

Problem with npm link <package>

Operating System: Windows 7, 64-bit Npm Version: 3.10.10 Node Version: 6.9.4 Hello, We are currently encountering issues with a custom npm package that we have published on our registry and installed in our Angular applications. Below are the di ...

Is Typescript reliable when working with a reference to a DOM element?

In this scenario, a function is provided with the task of obtaining a reference to a DOM element and executing certain actions: function getElementAndDoStuff() { // element: HTMLElement | null const element = document.getElementById('id'); ...

Creating a cucumber feature file from an Excel sheet or any other type of file: A step-by

I currently have an excel sheet containing various scenarios that I need to convert into a feature file. Can you assist me in accomplishing this task? Do you know of any plugins that can help streamline this process? Any guidance would be greatly apprecia ...

Can you explain the purpose of the .json() function in Angular2?

Can you explain the purpose of the .json() function within http requests in Angular2? Here is an example code snippet: this.http.get('http://localhost:8080/getName') .subscribe(res => this.names = res.json()); Is it correct to assume that t ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

Launch a component in a separate browser tab

I decided to open my component "template1" in a new tab, so I set up the path as follows: const routes: Routes = [ {path : 'template1' , component: Template1Component} ]; In the HTML file: <a mat-raised-button color="primary" target="_bl ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Encountering an error where `ng serve` is failing because it cannot locate the local workspace file (`angular.json`) for angular 5

Ensuring I'm in the correct directory. After successfully running `ng serve` earlier today, I am now encountering errors: Local workspace file ('angular.json') could not be found. Error: Local workspace file ('angular.json') coul ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...