I have a stream of Observable threads:
threads: Observable<{ [key: string]: Thread }>;
I want to create a function that iterates every object in my collection to find out if the id given in threadId parameter already exists. If it already exists, the function must return false.
My function does not work, but I do not know why. She always turns me 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;
}
EDIT :
I do not know how to do it. I am inspired by my function which allows me to return the thread according to the threadId given parameter:
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();
}
And after to subscribe I do this :
this.getThreadFromSubscription(objMessage.id)
.subscribe ((thread: Thread) => {
objMessage.thread = thread;
});
Should I be inspired to create my function or is it different?
Initializing my thread variable in threadService :
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;
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EDIT
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
When I subscribe to my knowNewThread function, it returns a list of boolean variables. Outside I would like that when I scoucirs to this function, it returns a single boolean variable true or false.
Here is what I wrote:
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;
}
});
When the id is already known, I would like to have my variable newThread to false, conversely for an unknown id, I would like the variable newThread to be true.