将数组值拆分为Angular

时间:2017-11-13 04:44:15

标签: javascript arrays json angular

如何将这一系列错误分解为新行?我尝试使用“\ n”并且它不会在Angular中分成几行?

  

JSON

{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}
  

error.ts

error => {
             alert("ERROR" + "\n" +  error.error.error + "\n");    
             console.log(error.error.error);
          });

4 个答案:

答案 0 :(得分:0)

问题是数组中的error.error.error并且您按原样打印它。

试试这个



var error = {
"headers": {
	"normalizedNames": {},
	"lazyUpdate": null
},
"status": 404,
"statusText": "Not Found",
"url": "http://sample.com",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://sample.com: 404 Not Found",
"error": {
	"error": [
	"Error1",
	"Error2",
	"Error3"
	]
}
}
var alertString = 'error ';
for (var i = 0; i < error.error.error.length; i++) {
alertString = alertString + '\n ' + error.error.error[i];
}
alert(alertString);
 console.log(alertString);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在HTML页面中显示错误时,您可以使用array#join()<br>插入分隔线。如果您想在alert()console中显示错误,可以array#join('\n')

var error = {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"http://sample.com","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://sample.com: 404 Not Found","error":{"error":["Error1","Error2","Error3"]}}
alert(error.error.error.join('\n'));
document.write(error.error.error.join('<br>'));

答案 2 :(得分:0)

在组件文件中保留错误并在HTML中重复该操作

TS文件

error : any ={
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}

HTML文件

<div *ngFor="let err of error.error.error">{{err}}</div>

答案 3 :(得分:0)

试试这段代码,

error => {
             alert("ERROR" + "\n" +  error.error[0] + "\n" +  error.error[1] + "\n" +  error.error[2]);    
             console.log(error.error);
          });