在Angular4.x中使用Rxjs请求数据,发现多次请求会造成n+1次请求次数,极大地影响性能,目前只能采用最笨拙的依次声明对应Subscription对象一一手动取消订阅,感觉不是正常办法,想请教更好的解决方式,示例代码如下:
service:
getRuleHitList(): any {
const formData = {
'uuid': this.orderNo
};
this.$http
.post(this.HOST.host + '/api/bqsBlackList', formData)
.subscribe(res => {
console.log(res);
this.RuleHitSubject.next(res);
})
}
component:
ruleSubscription: Subscription;
getRule() {
this.service.getRuleHitList();
this.ruleSubscription = this.service.RuleHitSubject.subscribe(res => {
if (res && res.code === '0') {
if (res.strategySet || res.Rule) {
this.ruleListFlag = true;
this.ruleList = res;
}
} else {
this.ruleListFlag = false;
}
this.ruleSubscription.unsubscribe()
})
上述getRule会在当前页面多次用到,且component不会销毁,因此不加unsubscribe()手动取消订阅页面会越来越卡,总感觉自己用的不对,请大佬不吝赐教;
你这么做就复杂了啊。。。
你首先在component一个调用service中的
getHttpRuleList()
方法来发一个http
请求,然后订阅了这个请求的结果,并将这个结果传递给了RuleHitSubject
, 又在component中来订阅这个RuleHitSubject
,来拿到http返回的结果, 是不是有点多此一举了呢?首先,http请求可以不用直接就订阅的,我们可以直接返回这个observable。
然后在component中直接订阅这个observable, 将component中的订阅作为一个流的终点。
所以你的代码可以改成这样:
service:
component:
而针对订阅,通常都要在组件销毁的时候来取消订阅,以防订阅的引用在应用中越来越多。