Angular 2-在数组中查找实例 [英] 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
我有一些模拟数据
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
我需要一些有关如何在调用logIn函数时检查该用户名实例的信息
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-在数组中查找实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!