After spending much time searching for a response to this answer: how to download a simple image from my API restful server written in Node.js into an Angular component app, I finally found a beautiful answer in this web Angular HttpClient Blob. Essentially it consist on:
API Node.js restful:
/* After routing the path you want ..*/
public getImage( req: Request, res: Response) {
// Check if file exist...
if (!req.params.file) {
return res.status(httpStatus.badRequest).json({
ok: false,
msg: 'File param not found.'
})
}
const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);
if (!fs.existsSync(absfile)) {
return res.status(httpStatus.badRequest).json({
ok: false,
msg: 'File name not found on server.'
})
}
res.sendFile(path.resolve(absfile));
}
Angular 6 tested component service (EmployeeService on my case):
downloadPhoto( name: string) : Observable<Blob> {
const url = environment.api_url + '/storer/employee/image/' + name;
return this.http.get(url, { responseType: 'blob' })
.pipe(
takeWhile( () => this.alive),
filter ( image => !!image));
}
Template
<img [src]="" class="custom-photo" #photo>
Component subscriber and use:
@ViewChild('photo') image: ElementRef;
public LoadPhoto( name: string) {
this._employeeService.downloadPhoto(name)
.subscribe( image => {
const url= window.URL.createObjectURL(image);
this.image.nativeElement.src= url;
}, error => {
console.log('error downloading: ', error);
})
}