首页 > 解决方案 > 当我尝试将 2 个 map() RxJS 运算符链接到 pipe() 时,为什么会出现此错误?

问题描述

在一个 Angular 项目中,我定义了这两种方法:

acceptArtistBid(bid: Bid): Observable<Bid[]> {
    console.log("acceptArtistBid() start !!!");

    // define a variable to hold the list of bids
    let listOfBids: Array<Bid>;

    // notice that the Observable is returned by this method and not subscribed in the service
    return this.findArtistBidsAppliedByCurrentWall(bid).pipe(
        // here you use the map of Observable to transform the list, and within this map you call the map Array method to run the transformation on each bid
        map(artistsBisdList => {
            return listOfBids = artistsBisdList.map(bid => {
                bid["test"] = "TEST";
                console.log("CURRENT BID: ", bid);
                return bid;
            })

        }),

        /* Assume updateFirestore$ is a method that returns an Observable representing the update operation.
           This second map operator returns an array of Observables
         */
        map(modiefiedListOfBids => modiefiedListOfBids.map(updatedBid => {
            console.log("UPDATED BID: ", updatedBid);
            // UPDATED updatedBid OBJECT ON FIRESTORE
        }));
        )
}

findArtistBidsAppliedByCurrentWall(bid): Observable<Bid[]> {
    return this.db.collection('bids',
        ref => ref.where("wallId", "==", bid.wallId))
        .snapshotChanges()
        .pipe(
            map(snaps => {
                const courses = this.convertSnaps<Bid>(snaps);
                return courses;
            })
        )
}

因此,正如您所看到的,该acceptArtistBid()方法首先调用findArtistBidsAppliedByCurrentWall()检索包含对象数组的 Observable的方法Bid,对于这个 Observable,我定义了一个pipe()RxJS 运算符链。第一个运算符(工作正常)简单地迭代由 observable 发出的该数组的每个 Bid 对象,并对每个对象执行修改(此时只需添加一个字段),构建listOfBids包含修改对象数组的 this。

然后我想链接第二个运算符,它将迭代map()链中上一步表示的新 Observable,以便在控制台中打印每个修改的元素并调用在 FireStore 数据库上更新它的方法(第二个功能不是尚未实施)。

问题是当我在我的pipe()链中添加这些第二张地图时:

map(modiefiedListOfBids => modiefiedListOfBids.map(updatedBid => {
    console.log("UPDATED BID: ", updatedBid);

    // UPDATED updatedBid OBJECT ON FIRESTORE
}));

IDE给我以下错误:

Type 'Observable<void[]>' is not assignable to type 'Observable<Bid[]>'.
  Type 'void[]' is not assignable to type 'Bid[]'.
    Type 'void' is not assignable to type 'Bid'.ts(2322)

怎么了?我错过了什么?我该如何解决?

标签: angulartypescriptrxjsobservableangular-observable

解决方案


您必须在 modiefiedListOfBids.map 函数中返回“Bid[]”类型的对象。

map(modiefiedListOfBids => modiefiedListOfBids.map(updatedBid => {
console.log("UPDATED BID: ", updatedBid);

// UPDATED updatedBid OBJECT ON FIRESTORE

return updatedBid; //return the modified object
}));

推荐阅读