【问题标题】:Angular 7 Typescript - Service ErrorHandle losing object instanceAngular 7 Typescript - 服务错误句柄丢失对象实例
【发布时间】:2019-06-14 16:29:45
【问题描述】:

当我从 Service api 调用中获得 404 或 500 时,我试图显示错误消息 [ngBootstrap Alert]。

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

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

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

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);

  }

ChildService.ts

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

    callApiMethod (){
     return this.http.get<Brand>(`ApiUrl`).pipe(

          catchError(this.handleError)
        );
     }
  }

AlertService.ts

@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;
  }
}

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',
}

当我尝试从 AlertService 调用 Add 方法时,出现以下错误

TypeError: 无法读取未定义的属性“添加”

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

【问题讨论】:

  • 好的代码 sn-ps:你能用你的imports 更新它们吗?

标签: angular typescript


【解决方案1】:

我猜你的问题在于没有绑定:

@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); 中的 BaseService 中的那一行引起的。

【讨论】:

    【解决方案2】:

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

    constructor(private msgService: AlertService) { }
    
    

    那么只有你能够执行“this.msgService”并且它不会未定义。

    干杯(y)

    【讨论】:

    • 是的,我试过了。它没有用..@Xesenix 得到了答案。
    【解决方案3】:

    您需要在 ChildServiceBaseService 中使用访问修饰符(public/private),以便您的服务引用与该属性一起可用。

    儿童服务

    @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) { }
    
    }
    

    【讨论】:

    • 是的,我试过了。它没有用..@Xesenix 得到了答案
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2021-10-05
    • 2016-01-20
    相关资源
    最近更新 更多