Mar*_*bia 4 javascript rxjs ionic-framework es6-promise angular
我用代码示例解释了我的问题
我有以下服务:
@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);
});
}
Run Code Online (Sandbox Code Playgroud)
从一个组件中,我需要调用转换为承诺的服务,以便稍后使用 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")
});
Run Code Online (Sandbox Code Playgroud)
有谁知道出了什么问题?
非常感谢您提前
mar*_*tin 16
使用toPromise()时需要确保源 Observables 完成。
Observables 可以发出多个值,因此toPromise()无法知道最后一个值是什么以及何时应该解析它返回的 Promise。
所以我的猜测是创建的源 Observable 之一this.get(...)永远不会完成。也许你想使用这样的东西Observable.zip(...).take(1)。
| 归档时间: |
|
| 查看次数: |
3990 次 |
| 最近记录: |