繁体   English   中英

角度材质对话框未关闭

[英]Angular Material Dialog Not Closing

在我的 Angular 应用程序中,我使用“材质”对话框来显示最终用户出现的任何错误消息。 我构建了一个错误服务,它可以有与服务器端 (http) 错误和客户端错误交互的方法。

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ErrorService {
  getClientMessage(error: Error): string {
    if (!navigator.onLine) {
      return 'No Internet Connection';
    }
    return error.message ? error.message : error.toString();
  }

  getClientStack(error: Error): string {
    return error.stack;
  }

  getServerMessage(error: HttpErrorResponse): string {
    console.log(error.statusText);
    return error.statusText;
  }

  getServerStack(error: HttpErrorResponse): string {
    // handle stack trace
    return 'stack';
  }
}

我正在使用 http 拦截器来获取 http 错误。

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      retry(1),
      catchError((error: HttpErrorResponse) => {
        return throwError(error);
      })
    );
  }
}

如您所见,我重试一次端点命中,然后捕获任何错误。 然后,我通过扩展 Angular ErrorHandler 的全局错误处理程序运行所有错误。

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
  HttpErrorResponse,
  HttpHeaders,
  HttpClient
} from '@angular/common/http';
import { PathLocationStrategy } from '@angular/common';
import { throwError, Observable } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
  // Error handling is important and needs to be loaded first.
  // Because of this we should manually inject the services with Injector.
  constructor(
    private injector: Injector,
    public dialog: MatDialog,
    private http: HttpClient
  ) {}
  // Function to handle errors
  handleError(error: Error | HttpErrorResponse) {
    const errorService = this.injector.get(ErrorService);
    const logger = this.injector.get(LoggerService);
    console.log('error: ', error);
    // Header options for http post
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      })
    };
    // Message variable to hold error message
    let message;
    // Variable to hold stacktrace
    let stacktrace;
    // Variable to hold url location of error
    const url = location instanceof PathLocationStrategy ? location.path() : '';
    if (error instanceof HttpErrorResponse) {
      // Server error
      message = errorService.getServerMessage(error);
      stacktrace = errorService.getServerStack(error);
    } else {
      // Client Error
      message = errorService.getClientMessage(error);
      stacktrace = errorService.getClientStack(error);
    }
    // log errors
    logger.logError(message, stacktrace);
    console.log('message: ', message);
    this.openDialog(message);
    return throwError(error);
  }
  openDialog(data): void {
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });

    dialogRef.afterClosed().subscribe((result) => {
      // Redirect back to home (dashboard)?
      console.log('in afterClosed: ' + result);
    });
  }
}

这是我有逻辑来检查错误是服务器端还是客户端的地方。 然后我点击了相应的错误服务方法。

发出我有真正的问题是该对话框。 如您所见,我正在打开一个对话框并显示一个错误组件。 该组件为最终用户提供了用户友好的视图。 这是我的错误对话框组件..

import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

@Component({
  selector: 'app-error-dialog',
  templateUrl: './error-dialog.component.html'
})
export class ErrorDialogComponent implements OnInit {
  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any,
    private dialogRef: MatDialogRef<ErrorDialogComponent>
  ) {}
  ngOnInit() {
    console.log('data in oninit: ', this.data);
  }
  /**
   * onCancelClick method
   * Closes the Material Dialog
   *
   * @returns :void
   *
   */
  onCloseClick(): void {
    console.log('data in onCloseClick: ', this.data);
    this.dialogRef.close('Eureka!');
  }
}

注意:我添加了 oninit 用于测试目的。 它不在我的原始代码中。

我在视图中添加了两个按钮来测试错误逻辑...

// html
<button (click)="throwError()">Error</button>
<button (click)="throwHttpError()">HTTP</button>
// component
throwError() {
    throw new Error('My Error');
  }
  throwHttpError() {
    this.http.get('someUrl').subscribe();
  }

当我单击客户端错误时,一切都按照设计进行。 当我单击 http 错误按钮时,它会打开对话框,ngoninit 中的 console.log 不会触发……当我单击关闭按钮时,它会触发,但 afterClosed 不会并且对话框不会关闭。

所以我想知道问题可能是什么......区域? 没有正确订阅可观察对象?

我想出了如何解决它......不确定确切的问题,但能够让我的代码工作。 这是我修改后的代码...

HttpErrorInterceptor

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse,
  HttpHeaders
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
import { PathLocationStrategy } from '@angular/common';
import { ErrorService } from './error.service';
import { LoggerService } from './logger.service';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(
    public dialog: MatDialog,
    private errorService: ErrorService,
    private logger: LoggerService
  ) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      retry(1),
      catchError((error: HttpErrorResponse) => {
        // Message variable to hold error message
        let errorMessage = '';
        // Variable to hold stacktrace
        let stacktrace;
        // Variable to hold url location of error
        const url =
          location instanceof PathLocationStrategy ? location.path() : '';
        // Header options for http post
        const options = {
          headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded'
          })
        };
        // server-side error
        errorMessage = this.errorService.getServerMessage(error);
        stacktrace = this.errorService.getServerStack(error);
        // log errors
        this.logger.logError(errorMessage, stacktrace);
        if (typeof errorMessage !== 'undefined') {
          this.openDialog(errorMessage);
        } else {
          this.openDialog('undefined');
        }
        return throwError(errorMessage);
      })
    );
  }
  openDialog(data): void {
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });

    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
      console.log('in afterClosed http: ' + result);
    });
  }
}

全局错误处理程序

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
  HttpErrorResponse,
  HttpHeaders,
  HttpClient
} from '@angular/common/http';
import { PathLocationStrategy } from '@angular/common';
import { throwError, Observable } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
  // Error handling is important and needs to be loaded first.
  // Because of this we should manually inject the services with Injector.
  constructor(
    private injector: Injector,
    public dialog: MatDialog,
    private http: HttpClient
  ) {}
  // Function to handle errors
  handleError(error: Error) {
    const errorService = this.injector.get(ErrorService);
    const logger = this.injector.get(LoggerService);
    // Header options for http post
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      })
    };
    // Message variable to hold error message
    let errorMessage;
    // Variable to hold stacktrace
    let stacktrace;
    // Variable to hold url location of error
    const url = location instanceof PathLocationStrategy ? location.path() : '';
    if (error instanceof Error) {
      // Client Error
      errorMessage = errorService.getClientMessage(error);
      stacktrace = errorService.getClientStack(error);
      this.openDialog(errorMessage);
    }
    // log errors
    logger.logError(errorMessage, stacktrace);
    return throwError(error);
  }
  openDialog(data): void {
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });

    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
      console.log('in afterClosed error: ' + result);
    });
  }
}

其他一切都保持不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM