我将用代码示例来解释我的问题。
我有以下的服务:
@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")
});
有人知道是什么问题吗?
非常感谢提前帮助。
.subscribe(v => ...)
只会处理next
通知,而不是完成通知。尝试使用.subscribe(v => ..., undefined, () => console.log('completed'))
,并查看它是否将“completed”打印到控制台。 - martin