首页 > 解决方案 > 如何通过asp.net和angular中的网络套接字传递接口?

问题描述

我正在开发一个使用 ASP.NET 编写的后端和 Angular 6 前端的项目。

我想通过网络套接字传递数据。该数据包含连接到一个接口的多个类。当我使用一个没有内部类和接口的类发送数据时,它可以工作,但当我使用接口时却不行。

在 Angular 端类上:

export class SocketMessage {
constructor(
public ID: string,
public Body: ISocketMessageType) { }
};

interface ISocketMessageType {
GetMessage(): string;
}

export class A implements ISocketMessageType {
public message: string;

public GetMessage() {
  return this.message;
}
constructor(message: string) {
    this.message = JSON.stringify(message);
    }
}

export class B implements ISocketMessageType
{
    public message: string;

    public GetMessage() {
        return this.message;
     }

      constructor(start: boolean) {
          this.message = JSON.stringify(start);
      }
 }

export class C implements ISocketMessageType {
    public message: string;

    public GetMessage() {
        return this.message;
    }
    constructor(var1: number) {
        this.message = JSON.stringify(speed);
    }
}

角链接端:

  connectToDevice() {
      this.socketService.connect().subscribe(
       (data) => {
         debugger;
        this.checkData(data);
      }
    );
  }

  checkData(data: SocketMessage) {
    if (data.Body instanceof A) {
      var info = data.Body as A;
      alert(info.message);
      this.router.navigate(['Home']);
    }
  }
}

服务器端:

[Serializable]
public class SocketMessage
{
    public string ID{ get; }
    public ISocketMessageType Body { get; }

    public SocketMessage (string ID, ISocketMessageType body)
    {
        this.ID= ID;
        this.Body = body;
    }
}

public interface ISocketMessageType
{
    string GetMessage();
}

[Serializable]
public class A: ISocketMessageType
{
    private string message;
    public string GetMessage()
    {
        return message;
    }

    public A(string msg)
    {
        this.message= message;
    }
}

[Serializable]
public class B: ISocketMessageType
{
    private bool start;
    public string GetMessage()
    {
        return start.ToString();
    }

    public B(bool start)
    {
        this.start = start;
    }
}

[Serializable]
public class C: ISocketMessageType
{
    private double var1;
    public string GetMessage()
    {
        return speed.ToString();
    }

    public C(double var1)
    {
        this.var1 = var1;
    }
}

但是我的输出是 ID:18 (这是正确的)和 body {} 为什么?

标签: asp.netangularwebsocket

解决方案


推荐阅读