如何在我的视图中显示Angular2异常

时间:2018-08-10 12:42:17

标签: javascript json angular javascript-objects

这是我用Angular2编写的Javascript代码。 这个问题很重要,但更重要的是:我如何在HTML页面上打印此错误,因为此页面将显示在移动Web视图中,以便另一侧的开发人员可以获取此错误。 即使JSON.stringify()无法正常工作。

let webSocketURL =  "ws://localhost:7000";
message = '';
webSocket:any;
try {
    this.webSocket = new WebSocket(webSocketURL);

    this.webSocket.onopen = (openEvent)=>{
        this.message = "WebSocket OPEN";
        this.webSocket.send('hello from client');
    };
    this.webSocket.onclose =  (closeEvent) =>{
        console.log('closeEvent',closeEvent);
        this.message = "WebSocket CLOSE"+ JSON.stringify(closeEvent);
        alert("WebSocket CLOSE: " + JSON.stringify(closeEvent, null, 4));
    };
} catch (exception) {
    console.error(exception);
    this.message = " Got exception" + exception ;
}

我的HTML代码如下

<p>
  This is stage 11 for socket demo and we are going to listion socket on ws://localhost:7000
</p>

<h3>Here is Message output ::{{message}} </h3>

我当前的输出如下:

you can see one one key-value is display in a message and in console its print all value

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

如果我没错,您想向其他开发人员展示该异常,如果可以,您可以使用此

let webSocketURL =  "ws://localhost:7000";
message : any;
webSocket:any;
try {
    this.message = null;

    this.webSocket = new WebSocket(webSocketURL);

    this.webSocket.onopen = (openEvent)=>{
       this.message = "WebSocket OPEN";
       this.webSocket.send('hello from client');
    };
    this.webSocket.onclose =  (closeEvent) =>{
        console.log('closeEvent',closeEvent);
        this.message = "WebSocket CLOSE"+ JSON.stringify(closeEvent);
        alert("WebSocket CLOSE: " + JSON.stringify(closeEvent, null, 4));
    };
} catch (exception) {
    console.error(exception);
    this.message = exception ;
}


<p>
  This is stage 11 for socket demo and we are going to listion socket on ws://localhost:7000
</p>

<h3 *ngIf="message">Here is Message output ::{{message | json}} </h3>

请注意,我已将消息类型更改为任何类型,以使其中包含对象