Angular 7第一个对象未​​正确推入数组

时间:2019-07-01 08:04:58

标签: angular typescript rxjs

我有一个聊天应用程序。我建立了新的连接,然后向他们发送消息:hello(我向该消息发送者)正在接收该消息并显示在其移动屏幕上。但是,在我的手机上,它没有显示在屏幕上,并且在可观察的订阅中,通过的所有内容都是[]。然后,当我关闭与伙伴交谈的窗口并重新打开它时,以前发送的所有消息都会显示在屏幕上,然后再发送更多消息。

component.ts

public messages$: Message[] - [];
private _messages: Subscription;

  public ngOnInit(): void {
    this._messages = this.chatService.messages$().subscribe((message: Message[]): void => {
      console.log('message received in subscription', message);
      this.messages$ = message;
      this.scrollToBottom();
    });
  }

  private ngOnDestroy(): void {
    this._messages.unsubscribe();
  }

chat.service.ts

 private messages: Message[] = new Array<Message>();
  private readonly bsMessages$: BehaviorSubject<Message[]> = new BehaviorSubject<Message[]>(this.messages);


  public messages$(): Observable<Message[]> {
    this.socket.fromEvent<Message>('message').subscribe((msg: Message): void => {
      if (msg.image) {
        msg.image = msg.image.replace('*', 'png');
        this.activeConversation.messages.push(msg);
        this.bsMessages$.next(this.messages);
        this.conversationStorage.set(this.activeConversation.id, this.activeConversation);
      } else {
        this.activeConversation.messages.push(msg);
        this.bsMessages$.next(this.messages);
        this.conversationStorage.set(this.activeConversation.id, this.activeConversation);
      }
    });
    return this.bsMessages$.asObservable();
  }

  public async sendMessage(msg: Message): Promise<void> {
    if (this.cameraPath) {
      await this.base64.encodeFile(this.cameraPath).then((base64File: string): void => {
        msg.image = base64File.replace('*', 'png');
        this.socket.emit('message', msg);
      });
      msg.image = this.webView.convertFileSrc(this.cameraPath);
    }
    await this.socket.emit('message', msg);
    this.activeConversation.messages.push(msg);
    this.bsMessages$.next(this.messages);
    this.conversationStorage.set(this.activeConversation.id, this.activeConversation);
  }

  public async setAsActiveConversation(user: Contact): Promise<void> {
    const { id } = user;
    this.activeConversation = await this.conversationStorage.get(id);
    if (this.activeConversation === null) {
      await this._newConversation(doctor);
      await this.conversationStorage.set(id, this.activeConversation);
    } else {
      this.activeConversation.messages.forEach((msg: Message): void => {
        if (msg.image) {
          msg.image = this.webView.convertFileSrc(msg.image);
        } else {
          msg.image = '';
        }
      });
      this.messages = this.activeConversation.messages;
      this.bsMessages$.next(this.messages);
    }
  }

感谢您的帮助

0 个答案:

没有答案