If you have specific requirements, here are a few options to consider...
filter + take(1)
this.fileService.getAvatarByUserId(2)
.pipe(
map((payload: Payload<FileModel[]>) => payload.result),
flatMap(uploads => uploads), // Flattens the array
filter(upload => upload.type === 'avatar'), // filters out non-avatar files
take(1) // retrieves only the first matching file
).subscribe(
console.log
);
OR
first(predicate function) -> my recommendation
this.fileService.getAvatarByUserId(2)
.pipe(
map((payload: Payload<FileModel[]>) => payload.result),
flatMap(uploads => uploads), // Flattens the array
first(upload => upload.type === 'avatar') // returns the first file that meets the condition
).subscribe(
console.log,
console.log // logs an error if no match is found after subscription completion
);
OR
filter + first
this.fileService.getAvatarByUserId(2)
.pipe(
map((payload: Payload<FileModel[]>) => payload.result),
flatMap(uploads => uploads), // Flattens the array
filter(upload => upload.type === 'avatar'), // filters out non-avatar files
first() // retrieves the first file in the filtered list
).subscribe(
console.log,
console.log // logs an error if no match is found after subscription completion
);
The first operator can handle errors when the specified condition is not met during subscription completion by using the error method -> check the subscriptions for the last two options (which may explain why I prefer this approach...)
view live demo here
amended to provide clearer explanation of the first operator based on @Jonathan Stellwag's feedback (thank you!!!)