代码之家  ›  专栏  ›  技术社区  ›  Roxy'Pro

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

  •  1
  • Roxy'Pro  · 技术社区  · 6 年前

    汽车可能位于不同的区域(如车库内、车库外)。。

    当我点击spot时,它的颜色会变为红色,就像拍摄的一样,但直到我关闭窗口并再次回来,我才能看到它。

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

    getCarSpotsByArea ()但它位于 parent-component , 所以我的问题是如何从子组件调用父方法?

    service

    下面是它的外观:

    enter image description here

    我的代码:

    当我点击 小孩 成分 车位 例如,现场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)}`);
            }
          }
        );
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Roxy'Pro    6 年前

    我所做的:

    @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 因为我父母的方法 getCarSpotsByArea 面积 作为一个论点,就这样!

        2
  •  0
  •   ABOS    6 年前

    除了上面提到的EventEmitter之外,还有两种从子组件调用父组件的方法

    1) 将父组件注入子组件

    export class ChildComponent  {
      constructor(private parent: ParentComponent) {
    
      } 
    
      callParentMethod() {
        this.parent.methodHandler();
      }
    }
    

    @Component({
      ...
      exportAs: 'parent'
    })
    export class ParentComponent  {
      ...
    }
    
    export class ChildComponent  {
      @Input() handler: Function;
      ... 
      callParentMethod() {
        this.handler();
      }
    }  
    

    在Html中,您可以将其引用为:

    <parent #p="parent">
      <child [handler]="p.methodHandler"></child>
    </parent>