Angular 7 打字稿 - 服务错误句柄丢失对象实例



当我从服务 api 调用收到 404 或 500 时,我正在尝试显示错误消息 [ngBootstrap 警报]。

我想通过alertComponent显示错误,并且我使用服务进行数据共享[AlertService.ts]。

当我对 api 的调用返回 404 时,我捕获错误并调用在我的服务基类中定义的 handleError 方法。

问题是我在基类中注入了警报服务,当我调用 HandleError 方法时,警报变量丢失了其实例并设置为未定义。

BaseService.ts

@Injectable({
  providedIn: 'root'
})
export abstract class BaseService {
  constructor(msgService: AlertService) { }
  public handleError(httpErrorResponse: HttpErrorResponse) {
    console.log(httpErrorResponse);
    let errorMessage = '';
    switch (httpErrorResponse.status) {
      case 400:
        errorMessage = 'Bad Request detected; please try again later!';
        break;
     case 404:
        const errorMsg = new Alert(AlertType.Danger, 'tracking-not-found');
        this.msgService.Add(errorMsg);
        break;
      case 500:
        errorMessage = 'Internal Server Error; please try again later!';
        break;
      default:
        errorMessage = 'Something bad happened; please try again later!';
        break;
    }
    return throwError(errorMessage);
  }

儿童服务网

    @Injectable({
      providedIn: 'root'
    })
    export class ChildService extends BaseService {
    constructor(alertService: AlertService){
    super(alertService)
    }
    callApiMethod (){
     return this.http.get<Brand>(`ApiUrl`).pipe(
          catchError(this.handleError)
        );
     }
  }

警报服务网

@Injectable({
  providedIn: 'root'
})
export class AlertService {
  alertMsg: Alert;
  constructor() { }
  public clear() {
    console.log('alert cleared');
    this.alertMsg = null;
  }
  public Add(alert: Alert) {
    this.alertMsg = alert;
  }
}

警报.ts

export class Alert {
  constructor(public alertType: AlertType,
    public msgCode: string,
    public icon?: string) { }
}
export enum AlertType {
  Success = 'success',
  Info = 'info',
  Warning = 'warning',
  Danger = 'danger',
}

当我尝试从警报服务调用添加方法时,出现以下错误

类型错误: 无法读取未定义的属性"添加">

我看到 msgService 变量以某种方式设置为取消定义。有什么帮助吗?

我想

你的问题在于不绑定:

@Injectable({
  providedIn: 'root'
})
export class ChildService extends BaseService {
  constructor(alertService: AlertService){
    super(alertService)
  }
  callApiMethod (){
    return this.http.get<Brand>(`ApiUrl`).pipe(
      catchError(this.handleError.bind(this)) // here we need to either bind or use arrow function
    );
  }
}

也就是说,如果您的错误是由该行引起的 this.msgService.Add(errorMsg); in BaseService .

你需要在 BaseService Class 的构造函数中定义服务的访问说明符:

constructor(private msgService: AlertService) { }

那么只有你才能做"this.msgService",它不会未定义。

干杯 (y(

需要在子服务和基本服务中使用访问修饰符(公共/专用(,以便服务引用随属性一起使用。

儿童服务

@Injectable({
  providedIn: 'root'
})
export class ChildService extends BaseService {
constructor(**private alertService**: AlertService){
super(alertService)
}

基本服务

 @Injectable({
  providedIn: 'root'
})
export abstract class BaseService {
  constructor(**private msgService**: AlertService) { }
}

最新更新