programing

현대 각도에서 손자부터 조부모까지 이벤트를 발산하는 방법은 무엇입니까?

iphone6s 2023. 6. 21. 22:25
반응형

현대 각도에서 손자부터 조부모까지 이벤트를 발산하는 방법은 무엇입니까?

여러 수준의 각도 구성 요소가 있는 경우 어떻게 사용할 수 있습니까?@Output사건을 아이에게서 조부모에게 보내는 것?

조부모:

<parent (handleClick)="grandmaHandleClick($event)">
<parent>
...
grandmaHandleClick(event) {
  console.log('grandma knows you clicked')
}

상위:

<child (handleClick)="handleClick($event)">
</child>

자식:

<div (click)="onClick()">Click button
</div>
...
@Output() handleClick = new EventEmitter
onClick() {
  this.handleClick.emit('clicked a button')
}

@Output이 몇 가지 구성 요소를 심층적으로 드릴링할 수 있도록 하려고 합니다. 이를 달성하는 가장 좋은 방법은 무엇입니까? 예를 들어 주시겠습니까?

두 가지 방법이 있을 수 있습니다.

  1. 사용.@output:

조부모

<parent (notifyGrandParent)="grandmaHandleClick($event)">
<parent>
...
grandmaHandleClick(event) {
  console.log('grandma knows you clicked')
}

상위 항목:

<child (handleClick)="childEvent($event)">
</child>

@Output() notifyGrandParent= new EventEmitter();
childEvent(event) {
  this.notifyGrandParent.emit('event')
}

코드에 아이가 제대로 구현되어 있어서 가기 좋습니다.

  1. 사용.BehaviorSubject경유로Service이 정도 수준의 중첩으로 실제로 다음과 같은 서비스를 만들 수 있습니다.EventService생성합니다.BehaviorSubject조부모가 직접 가입할 수 있습니다.또한, 이것을 만들기 위해.service더 구체적인 구성 요소, 당신은 이 서비스를 유지할 수 있습니다.module다른 세 가지 구성 요소(조부모, 부모 및 자녀)를 가질 것
export class EventService{

 private childClickedEvent = new BehaviorSubject<string>('');

  emitChildEvent(msg: string){
     this.childClickedEvent.next(msg)
  }

  childEventListner(){
     return this.childClickedEvent.asObservable();
   } 

}

그 다음에components:

하위 구성 요소

export class ChildComponent{
   constructor(private evtSvc: EventService){}

   onClick(){
     this.evtSvc.emitChildEvent('clicked a button')
   }
}

조부모

export class GrandComponent{
   constructor(private evtSvc: EventService){}

   ngOnInit(){
     this.evtSvc.childEventListner().subscribe(info =>{
         console.log(info); // here you get the message from Child component
      })
   }
}

참고하시기 바랍니다.@output사건이 발생하면 성분의 긴밀한 결합이 생성되므로 강력한 종속성(부모-자녀-손자)이 생성됩니다.구성요소가 재사용 가능하지 않고 이 목적을 위해 작성된 경우,@output또한 새로운 개발자에게 부모-자녀 관계가 있다는 메시지를 전달할 것이기 때문에 말이 됩니다.

데이터를 전달하는 서비스를 생성하면 데이터가 주입될 수 있는 다른 구성 요소에도 노출됩니다.serviceconstructor.

따라서, 그에 따라 결정이 내려져야 합니다.

rxjs/subject를 사용합니다. 관찰자이면서 동시에 관찰할 수 있습니다.

용도:

  1. 서비스에서 제목 속성 만들기:
import { Subject } from 'rxjs';

export class AuthService {
  loginAccures: Subject<boolean> = new Subject<boolean>();
}
  1. 하위 페이지/구성 요소에서 이벤트가 발생하는 경우:
logout() {
  this.authService.loginAccures.next(false);
}
  1. 상위 페이지/구성요소에서 제목을 구독합니다.
constructor(private authService: AuthService) {
  this.authService.loginAccures.subscribe((isLoggedIn: boolean) => {
    this.isLoggedIn = isLoggedIn;
  })
}

언급URL : https://stackoverflow.com/questions/56609069/how-to-emit-an-event-from-grandchildren-to-grandparent-in-modern-angular

반응형