I’m running a json-server database with some random data:
{
"status": [
{
"id": 3,
"uid": 1,
"isActive": false
},
{
"id": 4,
"uid": 3,
"isActive": true
}
]
}
and I’m using this function to fetch some data:
export async function getStatus(uid: number): Promise<Status>{
return fetch(`http://localhost:3000/status?uid=${uid}`).then(res => res.json())
}
And then, when I run this code:
function isActive(id: number): Observable<boolean>{
return from(getStatus(id))
.pipe(map(value => {
console.log (`Value of in map pipe: ${JSON.stringify(value)}`)
return value.isActive
}))
}
function main() {
isActive(1).subscribe({
next: (value => console.log('answer: ' + value))
})
}
main()
it returns this output:
Value of in map pipe: [{"id":3,"uid":1,"isActive":false}]
answer: undefined // <-----
The expected output:
Value of in map pipe: [{"id":3,"uid":1,"isActive":false}]
answer: false // <-----
Why do I get undefined instead of false?
>Solution :
In your console log I can see a array.
This code will work:
function isActive(id: number): Observable<boolean>{
return from(getStatus(id))
.pipe(map(value => {
console.log (`Value of in map pipe: ${JSON.stringify(value)}`)
return Array.isArray(value) ? value[0].isActive : false; // you can replace false with value.isActive
}))
}