gpt4 book ai didi

javascript - 当我在子组件中时,如何调用在父组件中创建/位于的方法

转载 作者:行者123 更新时间:2023-11-30 19:58:33 26 4
gpt4 key购买 nike

我正在开发 Angular 应用程序,它基本上是一个显示汽车位置的小应用程序,汽车可能在不同的区域(如车库内、车库外)。

当我点击该点时,它的颜色会变成红色,就像它被拍摄了一样,但我无法看到它,直到我关闭窗口并再次返回。

这里有2个组件,

一个 cars-spot-list 是父组件,car-spot 本身是子组件,因为它是列表的一部分。

所以我想做的是,当我点击汽车地点时,我正在更新我的数据库,因为该地点已被占用,我想再次调用我的方法 getCarSpotsByArea() 但它位于在父组件中,所以我的问题是如何从子组件调用父方法?

我可能会将其移至服务,但我想避免这种情况。

这是它的样子:

enter image description here

我的代码:

当我点击 child 组件 car-spot 例如 Spot 1 时,发生了这种情况:

 onClick(carSpot: CarSpot) {
this._carSpotService.changeCarSpotState(carSpot).subscribe(
// Successful responses call the first callback.
() => {
// CALL AGAIN SOMEHOW METHOD FROM A PARENT TO REFRESH MY VIEW
// for example: getCarSpotsByArea(carSpot.areaId);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('An error occurred:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
}
);
};
}

组件:car-spot-list组件

    getCarSpotsByArea(areaId: string) {
this._carSpotService.getCarSpotsByAreaId(areaId)
.subscribe(
data => {
this.carSpots = data;
},
// Errors will call this callback instead:
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(`Backend returned code ${err.status}, body was: ${JSON.stringify(err.error)}`);
}
}
);

最佳答案

我做了什么:

在我的子组件中,我创建了一个属性,它将发出我需要的值:

@Output() onUpdateCarSpot = new EventEmitter<string>();


onClick(carSpot: CarSpot) {
this._carSpotService.changeCarSpotState(carSpot).subscribe(
// Successful responses call the first callback.
() => {
// Here is the place where I needed to call parent method so here
// on success callback I've emitted value
this.onUpdateCarSpot(carSpot.areaId);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('An error occurred:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
}
);
};
}

在父组件 car-spot-list.component.html 中我接下来做了(是的一部分):

<car-spot (onUpdateCarSpot)="getCarSpotsByArea($event)"></car-spot>

我添加了一个 (onUpdateCarSpot),它实际上是我的子组件的 Output 事件发射器的名称,我只是告诉:

好的,当我发出一些东西时(它在子组件中回调),调用一个名为 getCarSpotsByArea 的方法并且我已经传递/发出 areaId 因为我 parent 的方法getCarSpotsByArea 接受 areaId 作为参数,仅此而已!

关于javascript - 当我在子组件中时,如何调用在父组件中创建/位于的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53654132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com