Hi everyone, I'm a new member of this forum and I've been struggling with a problem for the past few days. I am trying to create a loop that will iterate through every object in my collection.
Here is the variable I am working with:
threads: Observable<{ [key: string]: Thread }>;
Below is the function where I am attempting to create a loop using forEach or for:
findById(threadId: string) : Thread {
let foundThread: Thread = null;
this.threads.forEach(
(thread: Thread): void => {
if (thread.id === threadId) {
foundThread = thread;
}
},
null
);
return foundThread;
}
However, I encountered this error:
TS2345:Argument of type '(thread: Thread) => void' is not assignable to parameter of type '(value: { [key: string]: Thread; }) => void'. Types of parameters 'thread' and 'value' are incompatible. Type '{ [key: string]: Thread; }' is not assignable to type 'Thread'. Property 'id' is missing in type '{ [key: string]: Thread; }'
I also tried another solution, but it did not work either:
findById(threadId: string) : Thread {
let foundThread: Thread = null;
for (let thread in this.threads) {
if (thread.id === threadId) {
foundThread = thread;
}
}
return foundThread;
}
Thank you for your assistance :)
//////////////////////////////////////////////////////////////////////////
UPDATE :
Here is a different function that I have:
getThreadFromSubscription(threadId: string): Observable<Thread> {
return this.threads
.map( (threadDictionary: { [key: string]: Thread }) => {
for (let key in threadDictionary) {
if (threadDictionary[key].id == threadId)
return threadDictionary[key];
}
});
}
And here is how I intend to use the value returned by the above function:
addNewMessage(objMessage: any) : void {
objMessage.thread = this.threadService.getThreadFromSubscription(objMessage.id)
.subscribe ((thread: Thread) => {
if (objMessage.thread != null) {
const newMessage = new Message(objMessage);
this.addMessage(newMessage);
}
else {
const newThread: Thread = new Thread();
}
});
}
I would appreciate some clarification on whether my variable 'objMessage.thread' will indeed contain the thread value returned by 'getThreadFromSubscription'. Thank you for your guidance :)