我正在使用离子4。我从API获得结果,然后得到如下所示的结果
[
{"name":John,"age":20},
{"name":Peter,"age":35},
{"name":Alex,"age":15}
]
但是我只想获取名称以检查是否具有与我的条件相同的名称。但是我无法直接从API获取结果,我需要进行硬代码比较。这是我的代码:
this.http.get(SERVER_URL).subscribe((res) => {
const data = [
{ name: John, age: 21 },
{ name: Thomas, age: 25 },
];
const ppl= data.find(people=> people.name === 'alex');
console.log(ppl);
});
所以,我的第一个问题是如何直接从API获取名称,而不是像现在那样,我对来自API的结果进行硬编码。我的第二个问题是当我进行比较时,我想显示结果“已经存在”或“可以使用此名称”。因为如果我这样编写代码,将会得到错误类型'void'不能分配给类型'boolean':
const ppl= data.find((people)=> {
if(people.name === 'alex') {
this.text = 'already exist'
} else {
this.text = 'can use this name'
}});
console.log(ppl);
有人可以帮助我吗?非常感谢
答案 0 :(得分:0)
使用响应的内容代替定义数据; res
与您在data
中声明的内容完全相同。
this.http.get(SERVER_URL).subscribe(res => {
// If successful, res is an array with user data like the following
// [
// {name: "John", age: 21},
// {name: "Thomas", age: 25},
// ...
// ]
if (res.find(user => user.name === 'alex')) {
console.log ('Username has been taken');
} else {
console.log('Username is available');
}
});
取自MDN docs on Array.prototype.find():
find()
方法返回满足提供的测试功能的数组中第一个元素的值。否则,返回undefined。
在这种情况下
res.find(user => user.name === 'alex')
如果任何用户名都匹配 alex ,则将返回用户对象;如果undefined
属性均不匹配{{1 }}。
user.name
的值为alex
,而 user对象的条件为undefined
。
请记住,您正在将字符串与false
进行比较,例如,true
将与===
不匹配,如果您想研究其他比较字符串的方法,请看看this question。
您可能还想处理错误,如何处理错误取决于您自己,这取决于响应,但是您可以像这样访问预订中的Alex
:
alex
error
而不是this.http.get(SERVER_URL).subscribe(res => {
if (res.find(user => user.name === 'alex')) {
console.log ('Username has been taken');
} else {
console.log('Username is available');
}
}, error => {
console.log(error);
}, () => {
// There is also a 'complete' handler that triggers in both cases
});
如果您的API返回Object
而不是问题中的array
,您仍然可以遍历属性
Object
您可以使用Object.keys()而不是Object.values()来获取具有用户对象的数组,然后像以前一样使用array
,但这似乎效率较低,像这样:
this.http.get(SERVER_URL).subscribe(res => {
// If successful, res is an array with user data like the following
// {
// key1: {name: "John", age: 21},
// key2: {name: "Thomas", age: 25},
// ...
// }
let match = false;
Object.keys(res).forEach(key => {
if (res[key].name === 'alex') {
match = true;
}
});
if (match) {
console.log ('Username has been taken');
} else {
console.log('Username is available');
}
});