DarkW1nter
DarkW1nter

Reputation: 2851

Angular 6 - check http status of an image url

Im trying to check the http status code of an online image to check if it's been uploaded yet, I know this code is not correct, can someone tell me how to change it?

If the image has not loaded properly I show a backup image, I then want to poll the url until a status 200 is returned then change the image source to the url.

  getImageUrlStatus(url: string) {
    return this.http.get(url).subscribe(response => this.response = response.toString());
  }

Upvotes: 0

Views: 1437

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39432

Use a Subject or a BehaviorSubject for this.

Assuming that you'll use the imageUrl in a Component, in your service you can expose an Observable<string> via a Subject<string> or a BehaviorSubject<string>. You can initialize it with the defaultImagePath.

And when you get the response from your API, you can push a new value down the stream by calling the next method on it with the value.

This will translate to code something like this:

private imageUrl: BehaviourSubject<string> = new BehaviourSubject<string>(defaultImageResponse);
public imageUrl$: Observable<string> = this.imageUrl.asObservable();

...

getImageUrlStatus(url: string) {
  this.http.get(url)
    .subscribe(
      response => {
        const newImageResponse = response && response.toString();
        newImageResponse && this.imageUrl.next(newImageResponse);
      }
    );
}

You can now use this public Observable in your Component like this:

In your Component Class:

image$: Observable<string>;

constructor(private yourService: YourService) {}

ngOnInit () {
  this.image$ = this.yourService.imageUrl$;
}

And in your Component Template:

<div>
  <img [src]="image$ | async" />
</div>

Upvotes: 1

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30565

First, you cannot return subcription result in the way that you are doing

getImageUrlStatus(url: string) {
   this.http.get(url).subscribe(
     response => this.response = response.toString(),
     error => this.response = this.mydefaultImageResponse );
}

Upvotes: 2

Related Questions