Angular2表单如何将REST API返回的数组校验信息分行显示?
嘿,别发愁,这个问题很好解决,咱们一步步来搞定它:
方案一:每条错误单独显示为一个Alert(最简单,不用改太多代码)
首先修改你组件.ts里的错误处理逻辑,原来的this.error(data)是把整个数组直接传进去,现在咱们遍历这个错误数组,逐个调用alert服务的错误提示方法:
.subscribe( data => { if(condition){ // 这里注意你原来的写法是`condition = true`,这是赋值不是判断,要改成`condition === true`或者直接`if(condition)`哦! this.clear(); this.success(data); }else{ this.clear(); // 遍历服务端返回的错误数组,每条单独创建错误提示 data.forEach(errorMessage => { this.alertService.error(errorMessage); }); } })
这样改完,每条错误都会变成一个独立的Alert提示,自动分行(每个Alert是一个单独的块),新手友好,几乎不用改其他代码,直接就能生效。
方案二:所有错误放在同一个Alert里分行显示(适合想紧凑展示的场景)
如果你希望把所有错误放在一个Alert框里,用换行分隔,那需要做两处调整:
- 修改组件里的错误处理逻辑:把数组拼接成带HTML换行标签的字符串,同时告诉Alert服务要渲染HTML内容:
.subscribe( data => { if(condition){ this.clear(); this.success(data); }else{ this.clear(); // 把错误数组用<br>拼接成换行的HTML字符串 const combinedError = data.join('<br>'); // 调用error方法时传递isHtml选项,允许渲染HTML this.alertService.error(combinedError, { isHtml: true }); } })
- 调整Alert组件的模板和模型:
- 首先在
alert.model.ts里添加一个isHtml属性,用来标记是否要渲染HTML:export class Alert { id: string; type: AlertType; message: string; autoClose: boolean; keepAfterRouteChange: boolean; isHtml?: boolean; // 新增这个可选属性 constructor(init?: Partial<Alert>) { Object.assign(this, init); } } - 然后在
alert.service.ts里的error方法中支持接收这个选项:error(message: string, options?: { autoClose?: boolean; keepAfterRouteChange?: boolean; isHtml?: boolean }) { this.alert(new Alert({ type: AlertType.Error, message, autoClose: options?.autoClose ?? true, keepAfterRouteChange: options?.keepAfterRouteChange ?? false, isHtml: options?.isHtml ?? false })); } - 最后修改
alert.component.html,根据isHtml属性决定渲染方式(避免HTML被转义):<!-- 原来的{{ alert.message }}改成下面的判断 --> <div *ngIf="!alert.isHtml">{{ alert.message }}</div> <div *ngIf="alert.isHtml" [innerHTML]="alert.message"></div>
- 首先在
小提醒
你原来代码里的if(condition = true)是赋值操作,不是条件判断,要改成condition === true或者直接if(condition),不然会导致逻辑出错哦!
内容的提问来源于stack exchange,提问作者user9115375
相关产品推荐
相关产品推荐

