Skip to content

Instantly share code, notes, and snippets.

@alexytiger
Last active February 18, 2020 00:01
Show Gist options
  • Save alexytiger/eca1f185508c3ba0a0491070b1110422 to your computer and use it in GitHub Desktop.
Save alexytiger/eca1f185508c3ba0a0491070b1110422 to your computer and use it in GitHub Desktop.
import { ChangeDetectionStrategy, Component, Inject, OnInit, ViewChild , ElementRef } from '@angular/core';
import { MatDialogRef } from '@angular/material';
import { windowRefToken } from '../../../core/services/tokens';
import { Observable } from 'rxjs';
import { withLatestFrom, map, tap, filter, take } from 'rxjs/operators';
import { Store, select } from '@ngrx/store';
import * as fromPurchaseContract from '../../store/reducers';
import * as IpfsActions from '../../store/actions/ipfs-product-image.actions';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-show-ipfs-image',
templateUrl: 'show-ipfs-image.component.html',
styleUrls: ['show-ipfs-image.component.css']
})
export class ShowIpfsImageComponent implements OnInit {
@ViewChild('ipfsImage') imageRef: ElementRef;
image$: Observable<Blob>;
constructor(
private store$: Store<fromPurchaseContract.AppState>,
public dialogRef: MatDialogRef<ShowIpfsImageComponent>,
@Inject(windowRefToken) private windowRef: Window
) { }
ngOnInit() {
this.image$ = this.checkStore().pipe(
tap((blob) =>
this.imageRef.nativeElement.src = this.windowRef.URL.createObjectURL(blob)
)
);
}
checkStore(): Observable<Blob> {
return this.store$.pipe(
select(fromPurchaseContract.getImageBlob),
withLatestFrom(this.store$.pipe(select(fromPurchaseContract.getIpfsHash))),
tap( ([image, ipfsHash]) => {
if (!image) {
this.store$.dispatch(IpfsActions.downloadImage({ipfsHash}));
}
}),
map(([image, ipfsHash]) => image),
filter(image => !!image),
take(1)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment