My goal is to develop a secure login system with authentication on the Angular platform

login(data: any) {
    this.user.getUsers().subscribe(
      (users) => {
        const user = users.find((u) => u.username === data.username && u.userpassword === data.password);

        if (user) {
          // Valid username and password, navigate to the dashboard
          this.route.navigate(['dashboard']);
        } else {
          // Invalid username or password, handle accordingly (e.g., show an error message)
          console.error('Invalid username or password');
        }
      },
      (error) => {
        console.error('Error fetching users:', error);
      }
    );
  }

I encountered a problem with this code where the subscriber is deprecated, and after clicking the login button, it fails to open the dashboard page.

To resolve this issue, I am looking for a way to only allow successful logins with data that matches entries in a JSON file, which will then automatically navigate to the dashboard page.

Answer №1

In order to resolve the issue, it is essential to specify the function in subscribe where it should take place.

Instead of using the old syntax with next and error blocks as arguments, utilize an object with properties that define which function corresponds to each event. There are three main blocks:

  • next -> indicates that the observable has emitted a new value and may continue emitting values in the future
  • error -> signifies that an error has occurred in the observable stream
  • complete -> signals that the observable has finished emitting values and will no longer emit new values

code

login(data: any) {
    this.user.getUsers().subscribe({
      next:(users) => {
        const user = users.find((u) => u.username === data.username && u.userpassword === data.password);

        if (user) {
          // Valid username and password, redirect to the dashboard
          this.route.navigate(['dashboard']);
        } else {
          // Invalid username or password, handle accordingly (e.g., display an error message)
          console.error('Invalid username or password');
        }
      },
      error: (error) => {
        console.error('Error fetching users:', 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

The JSONObject contains a value, however it may sometimes return a null value

[ { "valve": "4679", "selling": "5516", "bal": "9075.4", "o id": "37", "invested": "11122", //<<<<<<<- this value returns null "aProfit": "1012", //<<<<<<<- this value returns null ...

What is the best way to change this specific JSON string into a Python dictionary?

Is there a way to transform the string below into a Python dictionary? string = [{"name":"sam"}] The end goal is to have it structured like this in Python: data = { "name" : "sam" } ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

When json_decode is called, it will parse a JSON string rather than returning

<?php $json=file_get_contents('php://input',true); $data = json_decode($json, true); print_r($data); ?> Here is the output: {"EventTitle":"Game","EventBody":"body","EventDate":"20 November, 2016","EventType":"party"} The JSON data that ...

There was an error encountered in the Recovery service Vault when attempting to add Policies for SQL Backup

I encountered an issue while setting up backup policies using Azure ARM Template for weekly SQL Backup. Any assistance would be greatly appreciated. It seems that the backupmanagementype for VM is AzureIaasVM, so for SQL it should be "backupManagementType ...

The module 'MatTableModule' could not be located within the '@angular/cdk/table' package during export

Having an issue with using where I'm getting the error message "export 'MatTableModule' was not found in '@angular/cdk/table'. Not sure what I might be doing wrong? You can find more details in my GitHub repository: https://githu ...

Accessing a ColdFusion JSON response from an API: How can you handle a field with a space in its name?

After making an API call to Airtable to create a new record in our order table, the response from the Airtable API looks like this: { "id":"recj9wqdjnNzN3aiu", "fields": { "Branch":["rec5S0H7R87Q ...

Is there a way to remove a specific section from a JSON object when a particular pattern is detected

When using an API to fetch football data, I have observed that the data becomes corrupted when a specific pattern appears. An example of the correct data format is shown below: { "id": 150, "name": "bwin", " ...

unable to show image retrieved from JSON data

Looking to showcase the data from my JSON objects, which are displayed in 2 images below https://i.stack.imgur.com/yhqFy.png https://i.stack.imgur.com/DUgFO.png In the data, I have properties like c_name, max_slots, and an array slots. Within the array, ...

In React, the edit mode fails to display class attributes

When I attempted to combine both the creation and editing functionalities in one form, I encountered a problem. Specifically, I was able to retrieve the correct ID value when editing an element, but I struggled to access the attribute values. import { yup ...

Is it feasible to deliver a push notification on iOS without utilizing the "alert" attribute in a JSON payload?

Is there a way to send a JSON format without including the "alert" attribute and still have the notification appear? I've attempted to remove the alert attribute, but it seems to prevent the notification from showing up. Any suggestions on how to hand ...

Using Python to Handle Null Values in JSON Data

My task involves working with the data provided below: [{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}] Upon attempting to store this data in a Python variable for parsing purposes, I encounter the fo ...

sass: node_modules/ionic-angular/themes/ionic.variables.scss

Encountered error during the execution of Ionic Cordova build command sass: node_modules/ionic-angular/themes/ionic.functions.scss Full Error: [11:34:50] sass started ... [11:34:51] sass: node_modules/ionic-angular/themes/ionic.functions.scss, line: 35 ...

Using TypeScript to style React components with the latest version of Material UI, version

Styled typography component accepts all the default typography props. When I include <ExtraProps> between styled() and the style, it also allows for extra props. const StyledTypography = styled(Typography)<ExtraProps>({}) My query is: when I r ...

Retrieve single byte from a JSON object

I am working with a Byte array that is being returned in my JSON. JSON [{"template":167,255,1,30,179,0,218,0,2,88,1,184,0], "template2":null, "template3":null, "Client_Id":1160739}] How can I retrieve this byte array in Java? I attempted to return a St ...

Finding the imported function in Jest Enzyme's mount() seems impossible

I'm currently facing an issue where I need to mount a component that utilizes a function from a library. This particular function is utilized within the componentDidMount lifecycle method. Here's a simplified version of what my code looks like: ...

Ways to make the current day stand out in a date picker calendar

Utilizing the ng-bootstrap datepicker, I am attempting to showcase an inline calendar in my application. However, the calendar fails to display the current day correctly, as depicted below: Despite trying various solutions, I have been unable to rectify t ...

Which is better in Angular2: defining default property values in the constructor or inline?

When it comes to creating an object class in Angular 2, the common dilemma is whether to initialize values inline or within a constructor. But what exactly is the difference between the two approaches? export class Foo { id: string; name: string = &ap ...

What is the reason behind tsc disregarding the include and exclude options in tsconfig.json?

I am facing an issue with my tsconfig.json file: { "compilerOptions": { "target": "ES6", "lib": [ "DOM", "ES6" ] }, "include": [ "src/server/**/*&q ...