我正在尝试使用flatMap链接2个订阅,但flatMap中的“this”不是指我的组件,而是指MergeMapSubscriber。在运行时_this引用我的组件,但如果我在我的代码中使用它,则TypeScript不能编译
import { flatMap } from 'rxjs/operators';
this.payexMasterService.queryOk().flatMap(
(res: ResponseWrapper) => {
_this.templateData.dataSets[0].data[0] = res.json;
return _this.payexMasterService.queryError();
}
).subscribe(
(res: ResponseWrapper) => {
this.templateData.dataSets[0].data[1] = res.json;
this.data = Object.assign({}, this.templateData);
},
(res: ResponseWrapper) => this.onError(res)
);
完整的代码......
@Component({
selector: 'pay-pie',
templateUrl: './payex-master-pie.component.html',
styleUrls: []
})
export class PayexMasterPieComponent implements OnInit {
numOk: number;
numError: number;
currentAccount: any;
eventSubscriber: Subscription;
data: any;
options: any;
templateData: any;
constructor(
private payexMasterService: PayexMasterService,
private jhiAlertService: JhiAlertService,
private eventManager: JhiEventManager,
private principal: Principal
) {
this.templateData = {
labels: ['OK', 'Error'],
datasets: [{
data: [0, 0],
backgroundColor: [
'#36A2EB',
'#FF6384',
],
hoverBackgroundColor: [
'#36A2EB',
'#FF6384',
]
}]
};
}
loadAll() {
this.payexMasterService.queryOk().pipe(flatMap(
(res: ResponseWrapper) => {
this.templateData.dataSets[0].data[0] = res.json;
return this.payexMasterService.queryError();
}
)).subscribe(
(res: ResponseWrapper) => {
this.templateData.dataSets[0].data[1] = res.json;
this.data = Object.assign({}, this.templateData);
},
(res: ResponseWrapper) => this.onError(res)
);
}
ngOnInit() {
this.loadAll();
this.principal.identity().then((account) => {
this.currentAccount = account;
});
}
private onError(error) {
this.jhiAlertService.error(error.message, null, null);
}
}
额外的细节,所以堆栈溢出将接受帖子
答案 0 :(得分:0)
要访问组件的this
,您应该使用管道功能。
.pipe(flatMap(...))
。
在新版本的rxjs中,运算符称为mergeMap。 https://www.learnrxjs.io/operators/transformation/mergemap.html