当我尝试将 2 个 map() RxJS 运算符链接到一个 pipe() 时,为什么会出现此错误?

Why am I obtaining this error when I try to chain 2 map() RxJS operators into a 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() 方法检索包含 Bid 个对象数组的 Observable,为此我定义了一个 pipe() RxJS 运算符链。第一个运算符(工作正常)简单地迭代由 observable 发出的这个数组的每个 Bid 对象,并对每个对象执行修改(目前只是添加一个字段)构建这个包含修改对象数组的 listOfBids .

然后我想链接第二个运算符,它将迭代链中前一个 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)

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

您必须在 modiefiedListOfBids.map 函数中 return 一个 'Bid[]' 类型的对象。

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

// UPDATED updatedBid OBJECT ON FIRESTORE

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

你的第二个mapreturnsvoid,你应该改成:

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

该方法需要一个 Observable<Bid[]>,而您返回了一个 Observable<void[]>(不返回任何内容)。这就是您收到此错误的原因。