我是这个论坛的新手。几天来我一直在阻止我的问题。 我想创建一个循环来迭代我的集合中的每个对象。
这是我的变量:
threads: Observable<{ [key: string]: Thread }>;
我的函数我想为每个或为:
创建一个循环findById(threadId: string) : Thread {
let foundThread: Thread = null;
this.threads.forEach(
(thread: Thread): void => {
if (thread.id === threadId) {
foundThread = thread;
}
},
null
);
return foundThread;
}
但我有这个错误:
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; }'
我尝试了另一种解决方案,但它不再起作用了:
findById(threadId: string) : Thread {
let foundThread: Thread = null;
for (let thread in this.threads) {
if (thread.id === threadId) {
foundThread = thread;
}
}
return foundThread;
}
提前谢谢你:)
/////////////////////////////////////////////// ///////////////////////////
更新:
这是我的功能:
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];
}
});
}
这是我想要使用函数返回的变量的函数:
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();
}
});
}
我不确定我理解。我的变量'objMessage.thread'是否采用'getThreadFromSubscription'返回的线程值? 谢谢你的帮助:))
答案 0 :(得分:1)
threads
不是可以迭代的字典或列表。相反,它是一个事件流(Observable
)。流中发出的事件类型为dictionary<string, Thread>
。
你在说什么,是时不时地,你会有一个来自threads
Observable的新词典。您可以将.map
运算符应用于Observable,以对发出的每个字典进行一些处理:
this.threads.map((threadDictionary: { [key: string]: Thread }) => {
\\ do some processing on the threadDictionary
});
要查看字典中的每个键,您可以像这样迭代它:
for (let key in threadDictionary) {
if (threadDictioanry[key].id == threadId)
foundThread = threadDictionary[key];
}
由于threads
是一个可观察的,你需要在某个地方订阅它以消耗它发出的值。您可以修改函数以返回您可以订阅的Observable<Thread>
,以便在原始threads
流发出值时获取正确的线程:
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];
}
});
}
您可以这样订阅:
this.getThreadFromSubscription('1').subscribe((thread: Thread) => {
this.processMyThread(thread);
});