如何通过angular4在UI上显示错误消息

时间:2018-07-11 09:44:23

标签: angular

这是我的代码。在做什么当用户尝试删除具有引用的作用域时,我需要显示错误。后端使用的是Spring Boot。 Spring Boot正常返回。检查屏幕截图。

来自后端的响应:-

{
  "status" : null,
  "message" : "Cannot delete scope. It's having reference.",
  "code" : "cannot_delete_having_reference"
}

我的问题。我需要为显示错误消息而更改的内容。

删除这种方法

delete(id: number): Observable<Response> {
    return this.http.delete<Response>(this.url + '/' + id);
  }

  open(scope: Scope): void {
    this.openModal(scope)
      .then(result => {
        if (result) {
          this.isLoading = true;
          const seq = this.scopeService.delete(scope.id).pipe(
           catchError((err:Response) =>{
            let details = err.body;
            console.log(details);
            return Observable.throw(new Error());
         }),
            switchMap(() => {
              return this.scopeService.findAll();
            })
          );
          this.saveSubscription = seq.subscribe(scopes => {
            if (this.scopes.length !== scopes.length) {
              this.isLoading = false;
            }
            this.scopes = scopes;
          });
        }
      })
      .catch(() => {});
  }

2 个答案:

答案 0 :(得分:0)

您可以根据响应将布尔变量设置为true / false。然后在您的标记中添加一个ngIf评估值,并相应地显示错误文本的div。

例如 ScopeListComponent.ts

export class ScopeListComponent implements OnInit, OnDestroy {
  /**
   * The loading boolean needed before show result
   */
  hasError: boolean;

...etc ...
}

执行删除后,将hasError设置为true:

const seq = this.scopeService.delete(scope.id).pipe(
           catchError((err:Response) =>{
            this.hasError = true;
            let details = err.body;
            console.log(details);
            return Observable.throw(new Error());
         })

在您的标记 scope-list.component.html

<div ngClass="alert alert-danger" *ngIf="hasError">An error occurred</div>

答案 1 :(得分:0)

open(scope: Scope): void {
    this.openModal(scope)
      .then(result => {
        if (result) {
          this.isLoading = true;
          const seq = this.scopeService.delete(scope.id).pipe(
            switchMap(() => {
              return this.scopeService.findAll();
            }),
            catchError((err:HttpErrorResponse) =>{
              const errorObject: CustomizedError = err.error;
              this.messageService.add({ severity: 'error', summary: errorObject.message });
              this.messageService.clear;
              return this.scopeService.findAll();
           }),
           finalize(() => (this.isLoading = false))
          );
          this.saveSubscription = seq.subscribe(scopes => {       
            if (this.scopes.length !== scopes.length) {
              this.isLoading = false;
            }
            this.scopes = scopes;
          });
        }
      })
      .catch(() => {});
  }