【发布时间】:2017-08-18 13:10:41
【问题描述】:
我有一个 Observable 线程流:
threads: Observable<{ [key: string]: Thread }>;
我想创建一个函数来迭代我的集合中的每个对象,以确定 threadId 参数中给出的 id 是否已经存在。如果它已经存在,该函数必须返回 false。
我的功能不起作用,但我不知道为什么。她总是让我误会:
knowNewThread(threadId: string): boolean {
let newThread: boolean = false;
this.threads
.map((threadDictionary: { [key: string]: Thread }) => {
for (let key in threadDictionary) {
if (threadDictionary[key].id === threadId) {
newThread = true;
}
}
});
return newThread;
}
编辑:
我不知道该怎么做。我受到我的函数的启发,该函数允许我根据 threadId 给定参数返回 thread:
getThreadFromSubscription(threadId: string): Observable<Thread> {
return this.threads
.filter((threadDictionary: { [key: string]: Thread }) => {
return Object.keys(threadDictionary).some((key) =>
threadDictionary[key].id === threadId);
})
.map((threadDictionary: { [key: string]: Thread }) => {
for (let key in threadDictionary) {
if (threadDictionary[key].id === threadId)
{
return threadDictionary[key];
}
}
}).first();
}
订阅后我会这样做:
this.getThreadFromSubscription(objMessage.id)
.subscribe ((thread: Thread) => {
objMessage.thread = thread;
});
我应该受到启发来创建我的功能还是有所不同?
在 threadService 中初始化我的 thread 变量:
this.threads = messageService.messages
.map((messages: Message[]) => {
const threads: { [key: string]: Thread } = {};
messages.map((message: Message) => {
threads[message.thread.id] = threads[message.thread.id] ||
message.thread;
const messagesThread: Thread = threads[message.thread.id];
if (!messagesThread.lastMessage ||
messagesThread.lastMessage.date < message.date) {
messagesThread.lastMessage = message;
}
});
return threads;
});
/////////////////////////////////////// ///////////////////////////////////////// /////////////////////////
编辑
/////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////p>
当我订阅我的 knowNewThread 函数时,它会返回一个布尔变量列表。 在外面,我希望当我搜索这个函数时,它返回一个布尔变量 true 或 false。
这是我写的:
knowNewThread(threadId: string): Observable<boolean> {
return this.threads
.map((threadDictionary: { [key: string]: Thread }) => {
let newThread: boolean = false;
for (let key in threadDictionary) {
if (threadDictionary[key].id === threadId) {
newThread = true;
}
}
return newThread;
}).first();
}
newThread: boolean = false;
this.knowNewThread(objMessage.id)
.subscribe( (test: boolean) => {
if(test === true) {
this.newThread = true;
}
});
当 id 已知时,我希望变量 newThread 为 false,相反,对于未知 id,我希望变量 newThread 为 true。
【问题讨论】:
-
你似乎认为 Observable 是一个集合,或者一个包含某些东西的盒子。根本不是这样。 Observable 更像是一部电话。你打开手机(即订阅 observable),表示你想接听电话(即事件)。一段时间后,您会接到电话(即事件)。你不能只打开手机就看到所有的电话在等着你。抱歉,我只能说这些了。您确实需要了解 Observable 的含义,因为您尝试做的事情没有意义。
-
@JBNizet 我真的不知道该怎么做。我通过添加详细信息编辑了我的帖子
-
我无法回答。不是不知道你为什么首先使用 observables,这些方法的用途,它们的使用位置等。处理 observables 的一般方法是从服务中获取它们,在组件中订阅它们并存储它们在组件中发出的事件,并使用组件中的数据(而不是使用 observables)。因此,如果您需要显示线程,请将线程存储在您的组件(而不是 Observable)中并处理线程。
-
@JBNizet 我的线程变量已在 threadService 服务中初始化,然后我搜索这些线程以查看 id 是否已在使用中。我重新编辑了我的帖子
标签: angular typescript rxjs