我必须解决异步调用的问题。
场景:
makeReservation
方法返回Observable<SaveResponse>
。当调用者调用makeReservation
方法时应该执行
1)调用send3DRequest
并订阅它并等待success
事件
2)在success
事件中获取必要的详细信息并返回另一个异步方法:return this.reservationHttpService.save(X)
在我的实际实现中,我收到错误:Return statement is required for non-void return type
。
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>{
this.reservationHttpService.send3DRequest(reservationDto.threeDQueryDetails)
.subscribe(
successResponse => {
if(successResponse.enrolled === 'Y'){
reservationDto.transRef = successResponse.transactionRef;
reservationDto.acsUrl = successResponse.acsUrl;
reservationDto.paReq = successResponse.paReq;
return this.reservationHttpService.save(reservationDto);
}
else {
reservationDto.transRef = successResponse.transactionRef;
return this.reservationHttpService.save(reservationDto);
}
},
error => { throw new Error(error); });
}
-
然后,我尝试进行此更改(问题在代码中描述):
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>{
let saveResponse = new Observable<SaveResponse>(); //added change
this.reservationHttpService.send3DRequest(reservationDto.threeDQueryDetails)
.subscribe(
successResponse => {
if(successResponse.enrolled === 'Y'){
reservationDto.transRef = successResponse.transactionRef;
reservationDto.acsUrl = successResponse.acsUrl;
reservationDto.paReq = successResponse.paReq;
let result = this.reservationHttpService.save(reservationDto);
//HOW TO INSERT the result in saveResponse and notify about change ?
}
else {
reservationDto.transRef = successResponse.transactionRef;
let result = this.reservationHttpService.save(reservationDto);
//HOW TO INSERT the result in saveResponse and notify about change ?
}
},
error => { throw new Error(error); });
return saveResponse; //added change
}
欢迎任何想法:) 感谢。
答案 0 :(得分:1)
如果您查看方法定义:
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>
您希望makeReservation
方法返回Observable
类型SaveResponse
。但是你不会在这里归还任何东西。
您刚开始订阅reservationHttpService.send3DRequest
。
你应该宁愿:
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>{
return this.reservationHttpService.send3DRequest(reservationDto.threeDQueryDetails)
(注意返回)。
现在,如果我们从你的第二个例子开始(这可能是最好的主意),我会做类似的事情:
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>{
return this
.reservationHttpService
.send3DRequest(reservationDto.threeDQueryDetails)
.switchMap(response => {
let result;
if(successResponse.enrolled === 'Y') {
reservationDto.transRef = successResponse.transactionRef;
reservationDto.acsUrl = successResponse.acsUrl;
reservationDto.paReq = successResponse.paReq;
result = this.reservationHttpService.save(reservationDto);
}
else {
reservationDto.transRef = successResponse.transactionRef;
result = this.reservationHttpService.save(reservationDto);
}
return Observable.of(result);
}
)
.catch(err => {
// handle your error here
return Observable.of({});
})
}
并且在致电时忘记在makeReservation
订阅:
this.makeReservation(your_argument).subscribe();