0

The Requirement is to return two simple arrays from the localdb.

The function is:

public getCaricamentoVeloceConf(): Observable<any> {
    let res = new RespOrdiniGetsceltecaricamentoveloce();

    res.tipo = this._WebDBService.Configurazione_CV_Scelte.toArray();
    res.ordinamento = this._WebDBService.Configurazione_CV_Ordinamento.toArray();

    return Observable.of(res);
  }

The error message I get is:

Type 'Promise' is not assignable to type 'Tipo[]'

I think that is because the ToArray() function returns a promise.

Actually what I need is, to compose the res object with the two arrays but I don't know how to combine the two promise toArray() methods

Any solution to this?

4

2 回答 2

2

IndexedDB is asynchronous, so it is expected that returned value will be a promise of the result and not the result itself.

For TypeScript and ES2017 the natural way to handle promises is async..await. If the method is supposed to work with observables, promises should be transformed to observables. Since RxJS offers more extensive control flow features than ES6 promises, it makes sense to do it as early as possible, e.g. with forkJoin that works similarly to Promise.all and accepts both promises and complete observables as sources:

  public getCaricamentoVeloceConf(): Observable<any> {
    return Observable.forkJoin(
      this._WebDBService.Configurazione_CV_Scelte.toArray(),
      this._WebDBService.Configurazione_CV_Ordinamento.toArray()
    )
    .map(([tipo, ordinamento]) => Object.assign(
      new RespOrdiniGetsceltecaricamentoveloce(),
      { tipo, ordinamento }
    ))
  }
于 2017-10-09T10:32:45.697 回答
1

Try this:

import 'rxjs/add/observable/fromPromise'; 
import { Observable } from "rxjs/Observable";

public getCaricamentoVeloceConf(): Observable<any> {   
    var res = new RespOrdiniGetsceltecaricamentoveloce();
    return Observable.fromPromise(
        this._WebDBService.Configurazione_CV_Scelte.toArray().then(tipo => {     
            res.tipo = tipo;
            return this._WebDBService.Configurazione_CV_Ordinamento.toArray();
        }).then(ordinamento => {
            res.ordinamento = ordinamento;
            return res;
        })
     );
  }

于 2017-10-09T10:14:26.567 回答