我有一些代码可以与您分享。它来自Ionic 2项目。我认为这是不好的做法,所以我想重构它。
我将base64中的图像发送到API,API将图像保存为服务器上的.png,然后在API服务器上向我发回带有此图像URL的响应。 应用程序在等待API响应时显示加载屏幕,因此您无法同时进行多个调用。 API也会回复每个调用1个响应,就是这样。
这是简单的电话:
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);
}
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
});
}
现在,getImageFromAPI()
由(click)
触发。所以,如果我点击一次,我会得到这个控制台日志:
1,"socialImageSubscription", www.apidomain.com/url1
第二次点击:
2,"socialImageSubscription", www.apidomain.com/url2
3,"socialImageSubscription", www.apidomain.com/url2
第三次点击:
4,"socialImageSubscription", www.apidomain.com/url3
5,"socialImageSubscription", www.apidomain.com/url3
6,"socialImageSubscription", www.apidomain.com/url4
因此,每次访问getImageFromAPI()
时,它都会创建一个新订阅,而之前的订阅仍然有效。
如何正确编写此代码?
答案 0 :(得分:1)
试试这个:它应该可以解决您的问题。
private getImageFromAPI(canvasURI) {
this._api.getImgUrl(canvasURI).subscribe((res:any) => {
this.i++;
console.log(this.i, 'socialImageSubscription', res.data);
// doing something with the response
}).unsubscribe(); // unsubscribe here
}
立即取消订阅,以便您不会激活订阅。此外,您还不需要订阅变量。
答案 1 :(得分:0)
玩了一下,找到了我要找的东西:
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 });
return this.http.post(
'my-api-url.com',
postData,
options
)
.retry(3)
.toPromise()
.then((res) => {
var body = res.json();
return body;
})
.catch(this.handleErrorPromise);
}
import { ApiService } from '../shared';
...
private i = 0;
constructor(private _api: ApiService) {}
private getImageFromAPI(canvasURI) {
this._api.apiImgUrl(canvasURI).then((res:any) => {
this.i++;
console.log(this.i, 'socialImageSubscription', res.data);
// doing something with the response
});
}
代码更容易阅读,并删除无用的订阅。控制台日志是您所期望的。首先点击:
1,"socialImageSubscription", www.apidomain.com/url1
第二次点击:
2,"socialImageSubscription", www.apidomain.com/url2
第三次点击:
3,"socialImageSubscription", www.apidomain.com/url3