我从数据库中创建了两个observable:
const roomData$ = estab
.query()
.where('estab.type', 'like', 'rooms')
.then((rooms) => {
rooms.forEach((room) => {
observer.next(room.data);
});
});
}).map(data => ({
roomsData: [
...data.rooms,
],
}));
const hotelData$ = Observable.create((observer) => {
estab
.query()
.where('estab.type', 'like', 'hotels')
.then((hotels) => {
hotels.forEach((hotel) => {
observer.next(hotel.data);
});
});
}).map(data => ({
hotelsData: [
...data.hotels,
],
}));
const hotelContentData$ = Observable.concat(roomData$, hotelData$);
hotelContentData$.subscribe((data) => {
fs.appendFile('data.json', (err) => {
if (err) throw err;
console.log('file has been appended!);
}
})
在data.json
文件中,我只找到了从roomData$
可观察数据中收到的数据。我改变了Observable.concat(hotelData$, roomData$)
中的顺序,现在我得到了酒店可观察的数据。为什么只执行一个Observable?如何执行这两项操作并从hotelData$
和roomData$
获取数据?
答案 0 :(得分:0)
Observable.concat
将从流中获取排放,直到该流完成,然后移至下一个流。由于您要创建自己的可观察序列,请务必完成每个序列。
const roomData$ = Observable.create( observer => {
estab
.query()
.where('estab.type', 'like', 'rooms')
.then((rooms) => {
rooms.forEach((room) => {
observer.next(room.data);
});
observer.complete(); // adding this will complete your stream.
});
}).map(data => ({
roomsData: [
...data.rooms,
],
}));
const hotelData$ = Observable.create((observer) => {
estab
.query()
.where('estab.type', 'like', 'hotels')
.then((hotels) => {
hotels.forEach((hotel) => {
observer.next(hotel.data);
});
observer.complete(); // adding this will complete your stream.
});
}).map(data => ({
hotelsData: [
...data.hotels,
],
}));
const hotelContentData$ = Observable.concat(roomData$, hotelData$);
hotelContentData$.subscribe((data) => {
fs.appendFile('data.json', (err) => {
if (err) throw err;
console.log('file has been appended!);
});
});