不用定义数据,而是使用响应的内容;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');
}
});
取自Array.prototype.find() 上的 MDN 文档:
该find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回未定义。
在这种情况下
res.find(user => user.name === 'alex')
如果任何用户名与alex匹配,或者没有任何属性匹配,则将返回一个用户对象。undefineduser.namealex
undefined在条件中计算为false和用户对象计算为true。
请记住,您正在将字符串与 进行比较===,因此,例如,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
如果您的 API 在您的问题中返回 anObject而不是arraylike,您仍然可以遍历属性
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');
}
});
代替Object.keys()你可以使用Object.values()来获取一个包含用户对象的数组,然后find()像以前一样使用,但这似乎效率较低,如下所示:
if (Object.values(res).find(user => user.name === 'alex')) {
console.log ('Username has been taken');
} else {
console.log('Username is available');
}