I am trying to request an image through a secure api. At the moment, I got the following for work (see All resources that I use below.
import { AssetsService } from '../../services/AssetsService'; import { Component } from '@angular/core'; @Component({ templateUrl: 'home.html', }) export class HomePage { public img; constructor( public assets_service: AssetsService ) { } public async ionViewDidEnter() { this.img = await this.assets_service.picture_request('test.png'); } }
My opinion
<img [src]="img | safe" />
Now I have seen an asynchronous channel that looks promising. As you might have guessed, I really don't want to use the viewmodel property for every image that I want to request via api, as described above.
I want to use the asynchronous call to picture_request
directly from the html view. This will save me from all the plumbing in the viewmodel. From what I read, something like this should work, but just that is not sad.
<img [src]="assets_service.picture_request('test.png') | async | safe" />
I am not sure if I am using async pipe
correctly or using the correct approach. If I'm not what should be my approach? Any help is appreciated. FYI: I use angular 2 in combination with ionic 2.
My other resources used are:
My safe pipe
import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor( private sanitizer: DomSanitizer ) { } transform(url) { return this.sanitizer.bypassSecurityTrustResourceUrl(url); } }
My asset service
import 'rxjs/Rx'; import { Headers, RequestOptions, ResponseContentType } from '@angular/http'; import { Injectable } from '@angular/core'; import { AppConfiguration } from '../app/AppConfiguration'; import { AuthHttp } from 'angular2-jwt'; @Injectable() export class AssetsService { constructor( private auth_http: AuthHttp ) { } public picture_request(filename: string) { return this.auth_http.post(AppConfiguration.base_url + 'assets/image', JSON.stringify({ filename: filename }), new RequestOptions({ responseType: ResponseContentType.Blob, headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) }) .map(res => res.blob()) .map(blob => URL.createObjectURL(blob)) .toPromise(); } }