Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in the FireBase database. Conversely, if invalid credentials are entered, a toast message displaying an error is shown.

Although I am successfully receiving responses from the Observable, including both tokens and errors, I would like to enhance the user experience by displaying a toast specifically for bad credentials.

Given my limited experience with Rxjs and reactive programming, I am seeking advice on how to seamlessly integrate code for showing the toast within the subscribe method as illustrated below:

logUser(){
      this.loginService.login(this.loginModel.userName,this.loginModel.password,this.loginModel.grant_type)
        .subscribe(token => {this.Token= token ,
                            console.log(this.Token.access_token)},
                              error => this.errorMessage = <any>error);      
         //<any>this.toast.create(this.toastOptions).present()             
      }

Answer №1

I've adjusted the formatting of your code to highlight where you should display a toast message for both successful and error scenarios:

logUser(){
    this.loginService.login(this.loginModel.userName,this.loginModel.password,this.loginModel.grant_type)
        .subscribe(
            token => {
                this.Token = token;
                console.log(this.Token.access_token);

                // Display a toast message for successful token retrieval here!
                // ...
            },
            error => {
                this.errorMessage = (<any>error);

                // Display a toast message for errors here!
                // ...

            });      
}

Since the subscribe function is asynchronous, it's important to handle success and error cases separately within their respective callbacks (token => { ... } and 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

Using the hook to implement the useContext function in React

I came across this definition export interface user{ email:string name:string last_name:string } export type UserType= { user: user; setUser:(user:user) => void; } const [user,setUser] = useState <user> ({ email ...

The error message "Property 'value' is not present on type 'EventTarget & HTMLSelectElement'" indicates that the 'value' property is not recognized on the Event

Here is the code snippet that I am working with: interface IHandleSelection { (value: string): any | void; } interface IPipeChangeEventValueToFunction { (handler: IHandleSelection): (event: React.ChangeEvent<HTMLSelectElement>) => void; ...

After installing Node.js on a Windows machine, the program 'npm' is not identified as an internal or external command, and cannot be executed as an operable program or batch file

I have been searching for a solution to this problem, but none of the suggestions I found seem to work for me. I am currently using a Windows 10 Laptop where I do not have administrative rights. My goal is to run my Angular + NodeJS application on this ma ...

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Error: Angular encountered an undefined variable when attempting to import 'node_modules/bootstrap/scss/grid'

Having some trouble setting up Angular with SCSS and Bootstrap. When attempting to run ng serve, I encountered the following error: ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Undefined variable. ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Looking to transform a timestamp such as "2021-07-18T9:33:58.000Z" into a more readable format like 18th July for the date or 9:33 am for the time using Angular?

Is there a way to convert the Timestamp format "2021-07-18T9:33:58.000Z" to display as 18th July (for date) or 9:33 am (for time) in an Angular 11 application? Currently, my code looks like this: const myDate = new DatePipe('en-US').transform ...

Navigating a webpage with Material select and routerLink in Angular 6

I am currently developing a feature that allows users to navigate to a page to access a list of documents from a policy. In addition, I am incorporating all policies so that users can easily move between them using a select form and direct you to the selec ...

Sharing precise API information between React components in React Components

I am currently learning react and facing an issue with sending data to other component files. I am trying to verify a user login from a backend API within an if statement, and if successful, I want to send the user ID to another component file. However, ...

Deploying Initial Node+Express+Angular Application in Production

Embarking on my first endeavor to develop a Node.js Express app with Angular 7 for deployment in production has me pondering the following: What is the recommended folder structure for this project? Should I maintain separate projects for Node and An ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...

I'm looking to inject both default static values and dynamic values into React's useForm hook. But I'm running into a TypeScript type error

Below is the useForm code I am using: const { register, handleSubmit, formState: { errors, isSubmitting }, reset, getValues, } = useForm({ defaultValues: { celebUid, //props fanUid, // props price, // props ...

Exploring various instances of an Angular 2 component to showcase diverse data

In one of my Angular 2 applications, I have a basic side menu that displays a list of different classRoom options, each with its own set of users. To switch between the various class rooms, I use the routerLink feature provided by Angular. The issue I am ...

Can I create a unique Generic for every Mapped Type in Typescript?

I've got a function that accepts multiple reducers and applies them all to a data structure. For instance, it can normalize the data of two individuals person1 and person2 using this function: normalizeData([person1, person2], { byId: { init ...

Why is it necessary for me to manually include and configure all d3.js dependencies in the SystemJS config file?

Currently, I am utilizing the systemjs.config.js file for an Application built on Angular5.x. To implement DAG charts in the application, I installed npm install --save @swimlane/ngx-graph and npm install --save @swimlane/ngx-charts. I have set up a comp ...

Unraveling Complex Observables with RxJS

I am facing a challenge with Rxjs that I need help solving. The data returned from the API looks like this: [ { name : test1, code : [1, 2] }, { name : test2, code : [1, 2, 3] }, ... ] What I want to achieve using Rxjs is to t ...

What is the best way to take any constructor type and transform it into a function type that can take the same arguments?

In the code snippet below, a class is created with a constructor that takes an argument of a generic type. This argument determines the type of the parameter received by the second argument. In this case, the first parameter sets the callback function&apos ...

Using local fonts with Styled Components and React TypeScript: A beginner's guide

Currently, I'm in the process of building a component library utilizing Reactjs, TypeScript, and Styled-components. I've come across the suggestion to use createGlobalStyle as mentioned in the documentation. However, since I am only working on a ...

Navigating the onSubmit with Formik in React: Tips and Tricks

I have a query regarding my usage of Formik in my React application. Within the onSubmit function, I am making an API call to a service. If this call fails, I want to immediately stop the rest of the submission process without executing any further action ...