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

Need at least one of two methods, or both, in an abstract class

Consider the following scenario: export abstract class AbstractButton { // Must always provide this method abstract someRequiredMethod(): void; // The successor must implement one of these (or both) abstract setInnerText?(): void; abst ...

Encountering a problem retrieving information from a nested JSON array

When fetching data from an API in JSON format, I encountered a successful response. However, the issue lies in extracting direct values without keys. Let me display the response first: Response { "message": "Notification Sent Successfully.", "success ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Navigating from ASP.NET Core Web API to Angular: Redirecting seamlessly

Seems like I am facing an issue with Angular redirection within ASP.NET Core Web API in a shared deployment scenario. I am using ASP.NET Core 7 for the Web API, which was working fine with ASP.NET Core 6. Here is the build files structure captured in a sc ...

The for loop finishes execution before the Observable in Angular emits its values

I am currently using a function called syncOnRoute() that returns a Promise. This function is responsible for synchronizing my data to the API multiple times based on the length of the data, and it returns a string message each time. However, I am facing a ...

Encountering a type 'any' issue with the Authentication guard injection in Angular 17

I implemented a functional guard in Angular 17 import { Inject } from '@angular/core'; export const checkoutGuard: CanActivateFn = (route, state) => { const customerService = Inject(CustomerService); const router = Inject(Router); ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

Automatically dismiss modal upon submission

In the process of implementing a CRUD operation, I am trying to automatically close the modal upon submission. Using data-dismiss on the submit button only closes the modal without executing the functionality. What I need is for the functionality to execut ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...

What is the best way to access a JSON Array in php without using any specified keys?

I'm dealing with a JSON object created in JavaScript and passed to PHP via AJAX. The issue I'm facing is that I can't figure out how to assign keys to each JSON object within the JSON array. Here's an example of how the JSON array looks ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

404 Error message encountered across all routes in a Node TypeScript Azure Function App - Resource not located

I keep encountering a 404 Not Found error on all routes while requesting my API. I am struggling to correctly write the code. Here's an example of my code: host.json: { "version": "2.0", "extensions": { & ...

What is the best way to include npm dependencies from multiple registries in the package.json file?

Within my package.json file, I have specified dependencies, one sourced from the public registry and another from a private registry (specifically Artifactory). "dependencies": { "vue": "^2.4.4", //public registry "ce-ui": "http://myartifa ...

Testing a function that involves multiple HTTP requests through unit testing

I am struggling with writing a unit test for a function that indirectly triggers multiple HTTP requests. The service I am testing has the following structure: /* content.service.ts */ import { Injectable } from "@angular/core" import { ApiService } from ...

Determining if an object aligns with a specific type in Typescript

Hey there, I've got a little dilemma. Imagine I have a type called A: type A = { prop1: string, prop2: { prop3: string } } Now, let's say I'm getting a JSON object from an outside service and I need to check if that JSO ...

Can you explain the significance of the 'project' within the parserOptions in the .eslintrc.js file?

Initially, I struggle with speaking English. Apologies for the inconvenience :( Currently, I am using ESLint in Visual Studio Code and delving into studying Nest.js. I find it difficult to grasp the 'project' setting within the parserOptions sec ...

Prevent selecting dates beyond the current date in Formly Datepicker within Angular

How can I disable future dates in Formly with Material datepicker in Angular? Despite searching online, I am unable to find a solution! export class AppComponent { form = new FormGroup({}); model: any = {}; options: FormlyFormOptions = {}; fields: ...

When attempting to retrieve data in JSON format from the Google Directions API, sometimes the returned data is empty

As a beginner in the world of programming and iOS development using Swift, I am currently facing an issue while attempting to create a route between two points. func getDirections(origin: String!, destination: String!, waypoints: Array<String>!, tra ...

Error: Bootstrap CSS missing from app created with create-react-app-ts

I have a React application that was initially set up using create-react-app-ts. Although I have included bootstrap and react-bootstrap for navigation, the CSS styling from Bootstrap does not seem to be applied properly. The links do not display any styling ...