[英]Angular4 Chain of observables
我對可觀測鏈有問題,一張地圖不等待響應,這破壞了我的想法。 我有這樣的東西。 我里面有組件和功能。
Step3Component
addCardAndGotoStep3() {
this.checkout.newCard = this.appNewCard.newCard;
this.checkout.addCardAndGotoStep3(this.appNewCard).subscribe();
}
CheckoutComponent
addCardAndGotoStep3 (newCardForm) {
if( !newCardForm.isValid) { return; }
// billingUtilService.checkout.newCard = vm.newCard;
return this.initPaymentMethods()
.map( () => {
// billingUtilService.addCardUi(vm)
return this.billingUtilService.addCardByRest(this);
})
.switchMap( (newCardId) => {
const model = {};
console.warn('newCardId' + newCardId);
console.error(newCardId);
const card: any = {};
card.uuid = newCardId;
card.fourDigits = this.newCard.cardNumber.slice(-4);
card.name = this.newCard.name;
card.id = card.fourDigits;
this.billingUtilService.checkout.screenPaymentMethod = card;
this.routeService.gotoState('app.loggedIn.team.checkout.step-3');
return newCardId;
})
.catch( (response) => {
this.alertService.addValidationAlert(this.tr.TR_CARD_NOT_ACCEPTED);
return Observable.throw({response});
});
};
BillingUtilService
addCardByRest(vm) {
const req = this.createPaymentMethodRequest(vm.newCard);
return this.billingRest.addAccountPaymentMethod(req)
.map( (paymentMethodId) => {
console.warn('successs' + paymentMethodId);
return paymentMethodId;
})
.catch( (response) => {
console.log('it doesnt work');
return Observable.throw(response);
});
BillingRestService
addAccountPaymentMethod (accountPaymentMethodRequest) {
return this.http.post(this.restUrl + this.restPrefix + '/addAccountPaymentMethodCC', accountPaymentMethodRequest, {observe: 'response'})
.map( (response: any) => {
if (! this.utilService.isDefined(response.body)) {
return Observable.throw({});
}
return response.body.paymentMethodId;
})
.catch((response) => {
this.logger.debug("addAccountPaymentMethodCatch")
this.logger.exception('addAccountPaymentMethod : Ajax Error')(response);
return Observable.throw(response);
});
};
我對這部分代碼有疑問
.map( () => {
// billingUtilService.addCardUi(vm)
return this.billingUtilService.addCardByRest(this);
})
.switchMap( (newCardId) => {
const model = {};
console.warn('newCardId' + newCardId);
console.error(newCardId);
該switchMap不等待addCardByRest返回。 我混淆了什么嗎? 其他服務返回一個可觀察到的值,因此我不得不使用一些展平的運算符,但實際上它不起作用。
控制台輸出:
newCardId[object Object] checkout-controler.service.ts
Observable {_isScalar: false, source: Observable, operator: CatchOperator} checkout-controler.service.ts
succes: [here is the RightUUid] checkout-controler.service.ts
使用concatMap並訂閱最后一個可觀察對象,而不是使用switchmap。
.concatMap( () => {
// billingUtilService.addCardUi(vm)
return this.billingUtilService.addCardByRest(this);
})
.subscribe( (newCardId) => {
const model = {};
console.warn('newCardId' + newCardId);
console.error(newCardId);
}, error => {
// Do something with error here instead of catch
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.