0

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());
  }

2 Answers 2

2

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 );
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.