问题描述
我正在为一个应用程序构建一个虚拟登录,我需要在一个数组中检查用户登录的实例
Im building a dummy login for an app, and I need to check for an instance of the user logging in, within an array
我有一些模拟数据
import { User } from './user';
export const USERS: User[] = [
{username: 'Seth', password: 'youwillneverknow'},
{username: 'Peter', password: 'iforgot'},
{username: 'Frank', password: 'test123'},
];
我在 user.service 文件中使用的内容
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 {
}
字符串值来自我的 HTML 中的输入字段
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
推荐答案
要查找数组的实例,请使用:
To find an instance of an array use:
users.find(x => x.username == value);
这将返回 USER 数组中具有匹配用户名的对象.如果它不存在,它将返回 undefined.
This will return the object in the USER array that with the matching user name. It will return undefined if it doesn't exist.
您也可以使用 findIndex
,它将返回数组中与谓词匹配的项目的索引,如果不存在则返回 -1:
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.
这篇关于Angular 2 - 在数组中查找实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!