Reputation: 59
I have this JSON
: (this.url)
{
"user": [
{
"id": "1",
"name": "root",
"password": "root"
},
{
"id": "2",
"name": "clienttest",
"password": "123456"
}
]
}
and I have this service:
findUsers(id: number) : boolean {
return this.http.get(this.url)
.map((res: Response) => res.json());
.someOperator(to assert the id exist)...
}
I want to return true
if the user was found.
Is there some operator like filter
that can make this assert for me?
Upvotes: 1
Views: 579
Reputation: 15442
try to use Array.some()
method:
findUsers(id: number) : boolean {
return this.http
.get(this.url)
.map((res: Response) => {
let result = res.json();
return result.user.some(user => parseInt(user.id) === id)
})
}
Inline simulation:
const data = {
"user": [
{
"id": "1",
"name": "root",
"password": "root"
},
{
"id": "2",
"name": "clienttest",
"password": "123456"
}
]
}
// this will simulate http get resolve being processed by res.json()
const httpGet = Rx.Observable.of(data);
const findUsers = id =>
httpGet.map(data => data.user.some(user => parseInt(user.id) === id))
;
findUsers(1).subscribe(result => console.log(result));
findUsers(3).subscribe(result => console.log(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>
Upvotes: 1