【发布时间】:2020-08-19 20:03:12
【问题描述】:
我有一个具有以下方法的服务 AppRestService:
export class AppRestService implements OnDestroy {
private readonly onDestroy = new Subject<void>();
constructor(private http: HttpClient, private sessSvc: SessionActivityService) { }
ngOnDestroy() {
this.onDestroy.next();
}
getData(route: string): Observable<any> {
this.sessSvc.sendNotification("TEST works", 15);
return this.http.get<any>(route).pipe(
takeUntil(this.onDestroy),
catchError(this.errorHandler),
);
}
errorHandler(err: HttpErrorResponse) {
let restErr: IErrorObjHttp = new ErrorObjHttp();
restErr.errObj = err;
if (err.error instanceof ErrorEvent) {
restErr.type = "client";
restErr.message = `An error occurred: ${err.error.message}.`; // Client-side error
} else {
restErr.type = "server";
restErr.message = `Server returned code : ${err.status}, error message is ${err.message}.`; // Service-side error
}
console.log("Error:", restErr);
this.sessSvc.sendNotification(restErr.message, 15);
console.log("post-sendNotification():", restErr.message);
return throwError(restErr);
}
}
我从不同的组件调用此服务。问题是“this.sessSvc”(这是在此服务中调用以发送通知的另一个服务)在 errorHandler() 方法中未定义并给出错误。从 getData() 方法调用 errorHandler() 方法。
TypeError: Cannot read property 'sendNotification' of undefined
但是当“this.sessSvc”直接在 getData() 方法中调用并且能够sendNotification 时,它工作正常。我错过了什么?
这就是我从不同组件调用服务的方式
export class PlanComponent implements OnInit {
planList: any;
constructor(private service: AppRestService) { }
ngOnInit() {
this.planList = this.service.getData("/api/plans/hhjkhhk");
}
}
【问题讨论】:
-
两点,你们在哪里提供服务?在根?另外,在您的
PlanComponent中,您是否在某个时候在planList上使用了异步管道?如果没有订阅,getData将永远不会真正执行。 -
我还没试过你是怎么做的,但我想
catchError这样:catchError(error => this.errorHandler(error)) -
只是好奇,如果你使用这种风格的函数声明,它会起作用吗?
errorHandler=(err: HttpErrorResponse)=> { ... } } -
@GunnarB.
<ng-container *ngFor="let plan of (planList | async)">是在 PlanComponent 的 html 上使用异步管道 -
@DJBurb 是的,除非针对此特定问题,否则它工作正常
标签: javascript angular angular8