类型“ {}”上不存在属性“ received_messages”

时间:2019-06-05 11:11:52

标签: node.js angular

am尝试使用套接字io从节点服务器获取数据,并实时在有角度的前端显示数据。当我尝试将返回的数据分配给我的模型时,出现此错误

错误TS2339:类型'{}'不存在属性'received_messages'。

component.ts

export class AppComponent implements OnInit {
  public received_messages: RecievedMessages = new RecievedMessages();
  public sigle_messages: any;
  constructor(private webSocketService: WebSocketService){}

    ngOnInit() {
    this.webSocketService.listen("All message Event").subscribe( (data) => {
        if(data && data.received_messages){
          this.received_messages = data.received_messages;
        }
    });
   }
}

message.objects.ts

export class RecievedMessages {
  public id: number;
  public coding: string;
  public gateway_id: number;
  public message: string;
  public message_id: string;
  public received_date: string;
  public sent_from: string;
  public sms_port_id: number;
  public created_at: string;
  public updated_at: string;
  constructor() {
    this.id = null;
    this.coding = '';
    this.gateway_id = null;
    this.message = '';
    this.message_id = '';
    this.received_date = '';
    this.sent_from = '';
    this.sms_port_id = null;
    this.created_at = '';
    this.updated_at = '';
  }
}

web-socket-service.ts

  socket:any;
  // readonly  url: string = "ws://localhost:3000";
  readonly  url: string = "http://0e0d9f8c.ngrok.io";
  constructor() {
    this.socket = io(this.url);
  }


  listen(eventName: string) {

    return new Observable((subscriber => {
          this.socket.on(eventName, (data) =>{
           // subscriber.next(JSON.parse(data));
           subscriber.next(JSON.parse(data));
          });
    }));
  }

error TS2339: Property 'received_messages' does not exist on type '{}'.

1 个答案:

答案 0 :(得分:0)

您应该将type设置为observable,以便编译器知道将发出哪种类型,默认情况下,它是对象类型({}),因此它没有recieved_message属性,请添加

  listen(eventName: string) {

    return new Observable<RecievedMessages>((subscriber => {
          this.socket.on(eventName, (data) =>{
           // subscriber.next(JSON.parse(data));
           subscriber.next(JSON.parse(data));
          });
    }));
  }