简体   繁体   中英

Observables from Array typescript

I want to create an observable from array, but I am getting error (A tuple type element list cannot be empty) every time. I have tried a lot, but still it's not working.

 listdonationsHistory(): Observable<[]> {
     const donationsHistory = [
        {
          id :1,
          type :"Aeri",
          amount: 200,
          frequency: 'monthly',
          date: '17-09-2017',
          account:'ATYTYTYY6778'
        },
        {
          id :2,
          type :"Aeri",
          amount: 200,
          frequency: 'monthly',
          date: '17-09-2017',
          account:'ATYTYTYY6778'
        }
      ];
    return Observable.from(donationsHistory);
 }

The problem is in the function's signature:

listdonationsHistory(): Observable<[]>

Specifically, it's the return type. That is where the empty tuple is.

To declare the return type as an observable that emits an arbitrary array, you could use:

listdonationsHistory(): Observable<any[]>

However, in the implementation you are calling Observable.from and the returned observable will emit the array elements separately - in which case the return type should be Observable<any> .

If you want an observable that will emit array itself, you should use Observable.of instead of Observable.from .

I can see a problem there. The return type is not an array it is an object. If you want the observable to be an array use Observable.of instead of Observable.from

Try that:

    interface Somereturn {
      id: number;
    }

    listdonationsHistory(): Observable<Somereturn> {
        return Observable.from([{id: 2}, {id: 3}]);
    }

    listdonationsHistory(): Observable<Somereturn[]> {
        return Observable.of([{id: 2}, {id: 3}]);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM