错误TypeError:无法读取ChatComponent上未定义的属性“ init”

时间:2019-02-08 10:26:03

标签: angular ionic-framework socket.io

在我的项目ionic上工作以建立节点服务器和移动应用程序之间的实时连接(通过ionic进行开发)的过程中,我遇到了这个问题,我不知道该怎么办,谢谢您的参与。有帮助 我是初学者:)

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { v4 } from 'uuid';

interface Message {
  id: string;
  text: string;
  timeStamp: Date;
  type: string;

}

@Component({
  selector: 'chat',
  templateUrl: 'chat.html',
})

export class ChatComponent implements OnInit {
  pusher: any;
  constructor(private http: HttpClient) {}

  messages: Array<Message> = [];
  message: string = '';
  lastMessageId;
  showEmojis = false;
  score = {
    tone: '',
    score: 0,
  };

  sendMessage() {
    if (this.message !== '') {
      // Assign an id to each outgoing message. It aids in the process of differentiating between outgoing and incoming messages
      this.lastMessageId = v4();
      this.showEmojis = false;
      const data = {
        id: this.lastMessageId,
        text: this.message,
      };

      this.http
        .post(`http://localhost:4000/messages`, data)
        .subscribe((res: Message) => {
          const message = {
            ...res,
            // The message type is added to distinguish between incoming and outgoing             messages. It also aids with styling of each message type
            type: 'outgoing',
          };
          this.messages = this.messages.concat(message);
          this.message = '';
        });

    }
  }

  // This method adds classes to the element based on the message type
  getClasses(messageType) {
    return {
      incoming: messageType === 'incoming',
      outgoing: messageType === 'outgoing',
    };
  }

  ngOnInit() {
    const channel = this.pusher.init();
    channel.bind('message', (data) => {
      if (data.id !== this.lastMessageId) {
        const message: Message = {
          ...data,
          type: 'incoming',
        };
        this.showEmojis = true;
        this.score = data.sentiment;
        this.messages = this.messages.concat(message);
      }
    });

  }
}`

0 个答案:

没有答案