Search code examples
arraysangularangular2-services

Angular 2 - find instance in array


Im building a dummy login for an app, and I need to check for an instance of the user logging in, within an array

I have some mock data

import { User } from './user';

export const USERS: User[] = [
  {username: 'Seth', password: 'youwillneverknow'},
  {username: 'Peter', password: 'iforgot'},
  {username: 'Frank', password: 'test123'},
];

Which I use in my user.service file

import { Injectable } from '@angular/core';
import { User } from './user';
import { USERS } from './users.mock';

@Injectable()
export class UserService {
  getUsers(): Promise<User[]> {
    return Promise.resolve(USERS);
  }

  <some method here>

}

and in my component I need to write a method checking if the user exists in the array.

  logIn(value: string): void {

  }

The string value comes from a input field in my HTML

I need some input on how to check for an instance of that username when calling the logIn function


Solution

  • To find an instance of an array use:

    users.find(x => x.username == value);
    

    This will return the object in the USER array that with the matching user name. It will return undefined if it doesn't exist.

    You can also use findIndex, which will return the index of the item in the array that matches the predicate or -1 if it doesn't exist:

    users.findIndex(x => x.username == value);
    

    As for having a list of usernames and passwords, this is definitely not recommended authentication. I hope you are doing something else for a production application.