I have a bit of code to share with you. It's from an Ionic 2 project. I think it's bad practice what I did, so I want to refactor it right.
I'm sending an image in base64 to an API, the API saves the image as .png on the server, then sends me back a response with this image's URL on the API server. The app shows a loading screen while waiting for the API response, so you can't make multiple calls in the same time. Also the API replies with 1 response for each call, and that's it.
Here's the simple call:
api.service.ts
private _imgUrl = new Subject<string>();
public getImgUrl(imgURI: any): Observable<string> {
this.apiImgUrl(imgURI);
return this._imgUrl.asObservable();
}
private setImgUrl(url: any) {
this._imgUrl.next(url);
}
private apiImgUrl(imgURI: string) {
var data = {
src: imgURI
};
var postData = JSON.stringify(data);
var headers = new Headers({ 'Content-Type': 'application/json' });
var options = new RequestOptions({ headers: headers });
this.http.post(
'my-api-url.com',
postData,
options
)
.retry(3)
.toPromise()
.then((res) => {
var body = res.json();
this.setImgUrl(body);
})
.catch(this.handleErrorPromise);
}
my-module.ts
import { ApiService } from '../shared';
...
private socialImageSubscription: Subscription;
private i = 0;
constructor(private _api: ApiService) {}
private getImageFromAPI(canvasURI) {
this.socialImageSubscription = this._api.getImgUrl(canvasURI).subscribe((res:any) => {
this.i++;
console.log(this.i, 'socialImageSubscription', res.data);
// doing something with the response
});
}
Now, getImageFromAPI()
is triggered by (click)
. So if I click once, I get this console log:
1,"socialImageSubscription", www.apidomain.com/url1
On second click:
2,"socialImageSubscription", www.apidomain.com/url2
3,"socialImageSubscription", www.apidomain.com/url2
On third click:
4,"socialImageSubscription", www.apidomain.com/url3
5,"socialImageSubscription", www.apidomain.com/url3
6,"socialImageSubscription", www.apidomain.com/url4
So each time I access getImageFromAPI()
it creates a new subscription, while the previous subscriptions remains active.
How can I write this code properly?