5

I'm using angular2-jwt to authorize the requests. I've got a get request which retrieves multiple documents from the API.

A document can have multiple images which also need to be fetched using an authorized request. So obviously calling them directly with doesn't work.

I followed this example: https://stackoverflow.com/a/40862839/909723

I've got two questions:

Without the async i get : GET http://localhost:4200/[object%20Object] 404 (Not Found) And with the async i get : Invalid argument '[object Object]' for pipe 'AsyncPipe' I tried it with the 'data:image/jpg;' and without

Part of the template

<md-card *ngFor="let document of documents">

  <md-toolbar color="accent" *ngIf="getDocName(document)">
    <span class="nowrap">{{getDocName(document)}}</span>
    <span class="country-full-width"></span>
  </md-toolbar>

  <md-card-content>
    <div *ngFor="let image of getImages(document)">
        <img class="image" [src]="getImageSrc(image.image_id) | async" />
    </div>
  </md-card-content>

</md-card>

I've got a service which uses angular2-jwt - AuthHttp

@Injectable()
export class ImageService {

 constructor(public authHttp: AuthHttp, public http: Http, public sanitizer: DomSanitizer) {}

  getImageSrc(id, type){
    let url = Config.apiUrl + "/images/" + id + "/thumb.jpg"
    let headers = new Headers();
    headers.append('Content-Type', 'image/jpg');
    return this.authHttp.get(url,  {
                    headers: headers,
                    responseType: ResponseContentType.Blob
                })
    .map(res => {
        return new Blob([res["_body]"]], {
            type: res.headers.get("Content-Type")
        });
    })
    .map(blob => {
        var urlCreator = window.URL;
        return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
    })

  }

}

This is the function called in the template

getImageSrc(id)
{
  return this.imageService.getImageSrc(id)
      //.subscribe (
      //  data => data,
      //  err => console.log(err)
      //);
}

Hope someone can help

Community
  • 1
  • 1
Sephen
  • 1,111
  • 3
  • 16
  • 38

1 Answers1

0

I have faced the same problem and this solution helped: http://blog.jsgoupil.com/request-image-files-with-angular-2-and-an-bearer-access-token

Although you may need to change the way in which options are added to http request (in UrlHelperService) according to your angular version 2/4.

Also you need to change:

Observable

to

Observable<any>

all ower the place.

And

private _result: BehaviorSubject = new BehaviorSubject(null);

to

private _result: BehaviorSubject<any> = new BehaviorSubject('');
Yaroslav N.
  • 406
  • 1
  • 7
  • 10