我正在尝试创建一个循环以迭代我的变量线程:
threads: Subject<{[key: string]: Thread }> = new BehaviorSubject({});
通过尝试这个,我得不到我想要的东西。确实,我的变量threadDictionary [key]
返回false而不是将Thread对象返回给我。
var threadDictionary = this.threads.asObservable().map((threadDictionary: {[key: string]: Thread}) => {
return threadDictionary;
});
for( let key in threadDictionary ) {
console.log("threadDictionary", threadDictionary);
console.log("threadDictionary[key]", threadDictionary[key]);
if(threadDictionary[key].participants[0].name.startsWith(str)) {
return threadDictionary[key];
}
}
感谢您的帮助......
////// EDIT
searchArrayThreads: { [key: string]: Thread; }[];
searchThreads: Subject<{ [key: string]: Thread; }[]> =
new BehaviorSubject<{ [key: string]: Thread; }[]>(new Array<{ [key: string]: Thread; }>());
threadTest: Subject<Array<Thread>> = new Subject()
searchUser(): void {
this.searchArrayThreads = [];
let str;
let element = document.getElementById('chat-window-input');
if(element != null) {
str = (element as HTMLInputElement).value;
}
else {
str = null;
}
this.threadTest.next((<any>Object).values(this.threads.getValue()));
const check = (threadDictionary) => {
for (let key in threadDictionary) {
const thread = threadDictionary[key];
if(thread.participants[0].name.startsWith(str)) {
return thread;
}
}
};
this.threadTest.subscribe(newThreads => {
const r = check(newThreads);
console.log('newThreads', newThreads);
if (r) {
this.searchArrayThreads.push(r);
this.searchThreads.next(this.searchArrayThreads);
}
if(r) {
console.log('found !', r);
} else {
console.log('not found');
}
});
}
当我尝试时,它不起作用。我得到的印象是我的threadTest变量什么都不包含。 我将以前的threads变量添加到新的threadTest变量中,如下所示:
this.threadTest.next((<any>Object).values(this.threads.getValue()));
以下是我订阅流之前的功能:
displaySearchUser(): void {
this.searchUser().subscribe((thread: Thread) => {
if (thread !== undefined) {
this.searchArrayThreads.push(thread);
}
this.searchThreads.next(this.searchArrayThreads);
});
}
答案 0 :(得分:1)
嗨:)我认为可能会有一些关于主题概念的混淆。
来自https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md:
什么是主题? RxJS主题是一种特殊类型的Observable,允许将值多播到许多观察者。虽然普通的Observable是单播的(每个订阅的Observer都拥有Observable的独立执行),但是Subjects是多播的。
了解这一点,并且:
每个主题都是一个可观察者。
您需要订阅它才能从observable获取任何更改(和值)。它应该是这样的:
const check = (ths) => {
for (let i in ths) {
const thread = ths[i];
if (thread.participants[0].name.startsWith(str)) {
return thread;
}
}
};
threads.subscribe(newThreads => {
const r = check(newThreads);
if (r) {
console.log('found !', r);
}else {
console.log('not found :(');
}
});
你的线程变量应如下所示:
threads: Subject<Array<Thread>> = new Subject();
还有一件事,我认为你应该只使用Subject而不是BehaviorSubject,因为它会在开头发出一个空的(除非你想在开头发出一个初始值)。
整个例子都在jsfiddle中:https://jsfiddle.net/uLrgsr32/