我使用的是Angular 7,我有一个带有服务的组件:
在我的组件中,我有一个调用服务函数的函数:
export class ProfileComponent implements OnInit, OnDestroy
{
[...]
public deleteCar(nameCar: string)
{
this.carService.deleteCar(nameCar, this.errorDeleteCar, this.successDeleteCarAndUpdateView);
}
[...]
}
服务功能为:
export class CarService
{
[...]
public deleteCar(offerId: string, errorDeleteCar: (error: HttpErrorResponse) => void, successDeleteCarAndUpdateView: (nameCar: string) => void):void
{
this.deleteFavoriteService(nameCar)
.subscribe(
() =>
{
successDeleteCarAndUpdateView(nameCar);
},
(error) =>
{
errorDeleteCar(error);
}
);
}
[...]
}
我的组件中的函数successDeleteCarAndUpdateView
是:
export class ProfileComponent implements OnInit, OnDestroy
{
[...]
public successDeleteCarAndUpdateView(nameCar: string): void
{
console.log("This is printed");
this.updateCache(nameCar);
[...]
}
public updateCache(nameCar: string): void
{
[...]
}
[...]
}
我无法呼叫updateCache
,我收到以下消息:
ERROR TypeError: this is undefined
但是console.log是有效的。
但是,当我以正常的方式调用函数时,例如从构造函数调用函数,我没有问题。
完整消息错误为:
ERROR TypeError: this is undefined
successDeleteCarAndUpdateView profile.component.ts:795
deleteCar car.service.ts:62
RxJS 11
__tryOrUnsub
next
_next
next
_next
next
_next
next
notifyNext
_next
next
Angular 8
onLoad
invokeTask
onInvokeTask
invokeTask
runTask
invokeTask
invokeTask
globalZoneAwareCallback
您可以通过以下操作修复它:
this.carService.deleteCar(nameCar, this.errorDeleteCar.bind(this), this.successDeleteCarAndUpdateView.bind(this));
使得函数具有绑定到它们的正确CCD_ 3上下文。。。
或者这也会起作用,因为箭头函数将保持正确的this
上下文:
this.carService.deleteCar(nameCar, (err) => this.errorDeleteCar(err), (resp) => this.successDeleteCarAndUpdateView(resp));
但相反,我建议对你的服务进行这样的重组。。。
// return the observable.
public deleteCar(offerId: string):void
{
return this.deleteFavoriteService(nameCar);
}
在组件中,订阅。。。
public deleteCar(nameCar: string)
{
this.carService.deleteCar(nameCar).subscribe(
(response) => this.successDeleteCarAndUpdateView(response),
(err) => this.errorDeleteCar(err),
);
}
更新视图是组件的工作,所以将其留在组件中。让服务完成它的工作,调用API。
public successDeleteCarAndUpdateView()
中this
的上下文已丢失,因为该方法在服务.subscribe
中作为回调调用。
有两件事你可以在这里试试。
- 将
this
绑定到方法本身以保留其Component上下文
export class ProfileComponent {
constructor(
... stuff ...
) {
this.successDeleteCarAndUpdateView.bind(this);
}
}
- 重构服务,只需进行HTTP调用,并将组件交回一个它也可以订阅的Observable。这可以帮助维护上下文并避免类似的回调问题