我需要創建一個 Observable 來收集來自一些 http 請求的其他 observables。新的 observable 必須是相同物件型別的集合,但每個專案必須是唯一的。你能幫我寫出正確的方法來實作這個目標嗎?
// The result observable that I need
topicCollection$ = BehaviorSubject<Topic[]> = new BehaviorSubject<Topic[]>(null);
// Boolean observable of authentication
isAuthenticated: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
// Return default topic
get defaultTopics$(): Observable<Topic[]>{
return this.defaultTopic.asObservable();
}
// Return topics selected by Admin
get TopTopics$(): Observable<Topic[]>{
return this.topTopic.asObservable();
}
//Return topics selected by User
get userTopics$: Observable<Topic[]>{
return this.userTopic.asObservable();
}
//Return user settings
get userSettings$(): Observable<any[]>{
return this.userSettings.asObservable();
}
所以約束是:
- 如果用戶未登錄,則集合必須按此順序:defaultTopic、topTopic
- 如果用戶已登錄,則集合必須按此順序:defaultTopic、topTopic、userTopic
- 如果用戶已登錄,我將閱讀過濾默認主題的 UserSettings$(如果它們將被隱藏或顯示)
- 主題必須是唯一的(重復的主題僅在默認情況下且用戶主題可觀察)
我嘗試使用 combineLatest 和 forkJoin,但我不知道如何區分操作員和身份驗證觀察者。
我真的很感激一些提示!謝謝
uj5u.com熱心網友回復:
你可以嘗試這樣的事情。當然,由于您的問題不完整,因此這個答案也不完整。
您必須自己實作一些部分。盡管如此,以下應該是一個不錯的開始修補的地方。
get topicCollection$(): Observable<Topic[]> {
return this.isAuthenticated.pipe(
take(1),
switchMap(isLogged => {
// The easy part, merge arrays emitted from two separate streams
const mergeDefaultTop$ = forkJoin([
this.defaultTopics$.pipe(take(1)),
this.topTopics$.pipe(take(1))
]).pipe(
map((v: Topic[][]) => v.flat())
);
// If the user is logged in, merge then filter the merged topics.
return !isLogged ? mergeDefaultTop$ : mergeDefaultTop$.pipe(
switchMap(topics => this.userTopics$.pipe(
map(userTopics => [...topics, ...userTopics])
)),
switchMap(topics => this.userSettings$.pipe(
map(settings => topics
// You'll want to update this filter. I can't define it for you
// as I dont know what a topic is/ how it's labled, etc.
.filter(topic => topic !in settings)
// Filter to remove duplicats. You may want to better define
// equality depending on your use case (again, I can't do
// that for you with what you've provided)
.filter((value, index, self) =>
self.indexOf(value) === index
)
)
))
);
})
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436037.html
