[英]Why the 'toPromise()' doesn't work for me when
我用代码示例解释了我的问题
我有以下服务:
@Injectable()
export class PartidoProvider extends MyFirestoreProvider<Partido> {
constructor( public http: HttpClient,
public firestore: AngularFirestore) {
super('partidos', http, firestore);
}
buscarPartido ( jugador1: Jugador, jugador2: Jugador ) : Observable<Partido[]> {
let partidoGanaJugador1: Partido = new Partido();
let partidoPierdeJugador1: Partido = new Partido();
partidoGanaJugador1.jugadorGanador = jugador1.idDoc;
partidoGanaJugador1.jugadorPerdedor = jugador2.idDoc;
partidoPierdeJugador1.jugadorGanador = jugador2.idDoc;
partidoPierdeJugador1.jugadorPerdedor = jugador1.idDoc;
return Observable.zip( this.get(partidoGanaJugador1),
this.get(partidoPierdeJugador1),
(listaGanados, listaPerdidos) => {
return listaGanados.concat(listaPerdidos);
});
}
从一个组件我需要调用转换为promise的服务,以便稍后使用await等待数据返回,以便管理另一个实体中的注册。
接下来,我将展示对服务调用的测试代码:
async enviarResultado(){
let rival: Jugador;
let jugador: Jugador = this.authProvider.jugador;
let nombreRival: string;
let partido: Partido;
// Obtener partido del calendario para añadirle el resultado
nombreRival = this.myForm.controls['rival'].value;
rival = this.rivales.find( rival => rival.nombre == nombreRival);
// THIS WORKS
const sample = val => Observable.of(val).delay(5000);
const example = sample('First Example').toPromise().then(result => {
console.log('From Promise:', result);
});
// THIS WORKS
this.partidoProvider.buscarPartido(jugador, rival).subscribe(
resultado => {
console.log("El subscribe ha devuelto datos");
console.log(resultado);
},
error => {
console.error("Se ha producido un error al intentar buscar el partido para modificar el resultado")
}
);
// THIS DOESN'T WORK only 1 appears in the debug console (console.log ("1"))
console.log("1");
this.partidoProvider.buscarPartido(jugador, rival).toPromise()
.then( lista => {
console.log("2");
console.log("Promesa entra");
console.log("data:" + lista);
if ( lista && lista.length > 0){
partido = lista[0]
}
})
.catch( error => {
console.log("2");
console.error("Se ha producido un error al intentar buscar el partido para modificar el resultado")
});
有谁知道什么是错的?
非常感谢你提前
使用toPromise()
您需要确保源Observables完成。
Observable可以发出多个值,因此toPromise()
无法知道最后一个值是什么,何时应该解析它返回的Promise。
所以我的猜测是用this.get(...)
创建的其中一个源Observable永远不会完成。 也许你想使用像这样的Observable.zip(...).take(1)
。
toPromise函数实际上有点棘手,因为它不是真正的“运算符”,而是一种特定于RxJS的订阅Observable并将其包装在promise中的方法。 一旦Observable完成,promise将解析为Observable的最后一个值。
https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.