【问题标题】:How can I display Angular2 exceptions in my view如何在我的视图中显示 Angular2 异常
【发布时间】:2019-01-18 02:04:58
【问题描述】:

这是我用 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>

我目前的输出如下:

我做错了什么?

【问题讨论】:

  • JSON.stringify 不会列出所有属性,只会列出可枚举的属性。如果您想显示错误事件中的特定信息,请明确执行。

标签: javascript json angular javascript-objects


【解决方案1】:

如果我理解正确,你想向其他开发者展示异常,如果是,你可以使用它

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>

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

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 2016-08-28
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多