将Thread类型的变量添加到Observable类型的变量< {[key:string]:Thread}>

时间:2017-08-16 13:04:38

标签: angular typescript rxjs

以下是我启动变量线程的方法:

threads: Observable<{ [key: string]: 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;
  });

我想在变量线程中添加一个变量newThread:

const newThread: Thread = new Thread(objMessage.id, objmessage.participants);

我试过了:

threads = Observable.of([newThread]);

或者这个:

this.threads.subscribe((thread: Thread) => {
   threads.next(newThread);
});

但它不起作用。但是这种类型不合适。

/////////////////////////////////////////////// /////////////////////////////

编辑:

/////////////////////////////////////////////// /////////////////////////////

当我将我的线程变量更改为BehaviorSubject时:

threads: BehaviorSubject<{[key: string]: Thread }> = BehaviorSubject.create();

我修改了这个初始化:

this.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;
}).subscribe(threads => {
  this.threads.next(threads);
});

我说了这个:

addThread(newThread: Thread): void {
  this.threadService.newThreads.push(newThread);
  this.threadService.newThreadsId.push(newThread.id);

this.threadService.orderedThreads.next(this.threadService.newThreads);

let threads = this.threadService.threads.value;
this.threadService.threads.next(threads);
}

我有这个错误:

Cannot set property 'flo' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot set property 'tRev' of undefined

'flo'这是我的主题:

this.addNewMessageNewThread({
  "id": "flo",
  "author": "Flo Peron",
  "body": "COUUUUCOU",
  "title": "Groupe 158"
});

1 个答案:

答案 0 :(得分:0)

听起来你想要一个主题,而不是一个可观察的主题。具体来说,您可能想要一个行为主题,因为您想要修改当前值。

threads: BehaviorSubject<{[key: string]: Thread}>;

messageService.messages.map(...).subscribe(threads => {
  this.threads.next(threads);
});

addThread(key: string, thread: Thread) {
  let threads = this.threads.value;
  threads[key] = thread;
  this.threads.next(threads);
}