Raj*_*Gan 3 typescript angular
当我从 Service api 调用中获得 404 或 500 时,我试图显示错误消息 [ngBootstrap Alert]。
我想通过 alertComponent 显示错误,并使用服务进行数据共享 [AlertService.ts]。
当我调用 api 返回 404 时,我捕获错误并调用在我的服务基类中定义的 handleError 方法。
问题是我在我的基类中注入了我的警报服务,当我调用 HandleError 方法时,警报变量丢失了它的实例并设置为未定义。
基础服务.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);
}
Run Code Online (Sandbox Code Playgroud)
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)
);
}
}
Run Code Online (Sandbox Code Playgroud)
警报服务.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;
}
}
Run Code Online (Sandbox Code Playgroud)
警报.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',
}
Run Code Online (Sandbox Code Playgroud)
当我尝试从 AlertService 调用 Add 方法时,出现以下错误
类型错误:无法读取未定义的属性“添加”
我看到 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
);
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,如果您的错误是由 inthis.msgService.Add(errorMsg);中的那一行引起的BaseService。
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |