Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么';toPromise()';不';我什么时候不为我工作_Javascript_Angular_Ionic Framework_Rxjs_Es6 Promise - Fatal编程技术网

Javascript 为什么';toPromise()';不';我什么时候不为我工作

Javascript 为什么';toPromise()';不';我什么时候不为我工作,javascript,angular,ionic-framework,rxjs,es6-promise,Javascript,Angular,Ionic Framework,Rxjs,Es6 Promise,我用代码示例解释我的问题 我有以下服务: @Injectable() export class PartidoProvider extends MyFirestoreProvider<Partido> { constructor( public http: HttpClient, public firestore: AngularFirestore) { super('partidos', http, firestore);

我用代码示例解释我的问题

我有以下服务:

@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);
    });    
}
有人知道怎么回事吗

事先非常感谢

toPromise函数实际上有点棘手,因为它不是一个真正的函数 “operator”,更确切地说,它是一种RxJS特有的订阅 可观察并用承诺来包装它。这一承诺将解决问题 一旦可观测对象完成,可观测对象的最后发出值

当使用
toPromise()
时,您需要确保源观测完成

Observable可以发出多个值,因此
toPromise()
无法知道最后一个值是什么,以及何时应该解析它返回的承诺


因此,我的猜测是,使用
this.get(…)
创建的一个源观测永远不会完成。也许你想使用类似这样的
Observable.zip(…)。在代码中你可以看到Observable是如何完成的。在没有“toPromise()”的情况下调用同一个函数,并返回正确的数据。您的代码不会显示两个可观察对象的完成位置。使用
.subscribe(v=>…)
将只处理
下一个
通知,而不是完整的通知。尝试使用
.subscribe(v=>…,未定义,()=>console.log('completed'))
并确保它不会将
“completed”
打印到控制台中。您是对的。我看不到“已完成”。非常感谢。在代码中,您可以看到observable是如何完成的。在不使用“toPromise()”的情况下调用相同的函数,并返回正确的数据。
  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")
    });