如何将数据从 child 组件的守卫传递到 parent 组件?

How to pass data from guard of a child component to parent component?

我有一个 parent 组件,其中有一堆带有 link 的选项卡。每个选项卡都有一个 link,它将导航到 child 组件。 parent 选项卡有一个 header 数据,例如客户姓名、出生日期、性别...

parent 组件 .HTML 如下所示:

 <mat-card>
    <mat-card-header>
      <mat-card-title>
        <mat-chip-list aria-label="Title" class="table_title">
          <mat-chip color="primary" selected>Client Detail</mat-chip>
          <mat-chip color="accent" *ngIf="clientName">Client Name: {{ clientName }}</mat-chip>
          <mat-chip color="accent" *ngIf="clientAlias">DOB: {{ clientDOB }}</mat-chip>
          <mat-chip color="accent" *ngIf="clientAlias">Gender: {{ clientGender }}</mat-chip>

        </mat-chip-list>
      </mat-card-title>
    </mat-card-header>
    <mat-card-content>
      <nav mat-tab-nav-bar>
        <a mat-tab-link
          [routerLink]="['./demographics']"
          (click)="activeLink = 'demographics'"
          [active]="activeLink == 'demographics'">
          <mat-icon class="tab-icon">contact_page</mat-icon>
          Identifying Information
        </a>
        <a mat-tab-link
          [routerLink]="['./contacts']"
          (click)="activeLink = 'contacts'"
          [active]="activeLink == 'contacts'">
          <mat-icon class="tab-icon">contacts</mat-icon>
          Contacts
        </a>
      </nav>

      <router-outlet></router-outlet>
    </mat-card-content>
  </mat-card>

路由器出口将根据选项卡名称呈现适当的 child 组件。

Parent 组件 .ts 如下所示:

ngOnInit() {
    // Calling the resolver and updating the activeLink
    this.activeLink = this.route.snapshot.data.tab;

    // Set the header data
    this.route.data.subscribe(resolvedData => {
      if (resolvedData.headerData !== null) {
        this.clientName = resolvedData.headerData.fullName;
        this.clientDOB = resolvedData.headerData.dob;
        this.clientGender = resolvedData.headerData.gender;
      } else {
        this.router.navigate(['/clients']);
      }
    });
  }

导航(呈现)child 组件(人口统计)将允许用户编辑客户信息,例如姓名、性别、出生日期。

客户人口统计页面(组件)的保存是使用防护(停用)完成的,这意味着除非数据有效,否则用户无法导航到联系人页面或其他页面(选项卡)。

我的停用守卫如下所示:

if (model.dirty && model.valid) {
      // call the saving service
      this.clientService.UpdateClientIdentInfo(personId, model.getRawValue()).subscribe(updatedHeaderData => {
        // TODO: PASS updatedHeaderData TO THE PARENT COMPOENET
        this.snackBar.open('Data has been saved successfully!', '', {
          duration: 2000,
          horizontalPosition: 'center',
          verticalPosition: 'bottom',
          panelClass: ['snack-success']
        });
        return true;
      }, error => {
        return false;
      })
    }

此 API 调用 updatedHeaderData 的响应将包含我要传递给 parent 组件的新数据,因此它的所有 header 数据得到更新。

这是我的应用路由模型

{
    path: 'clients/:id',
    component: ClientDetailsComponent,
    resolve: {
      tab: ClientDetailsResolver,
      headerData: ClientDetailHeaderDataResolver
    },
    children: [
      {
        path: 'demographics',
        component: ClientIdentInfoComponent,
        resolve: { client: ClientIdentInfoResolver },
        canDeactivate: [ ClientIdentInfoGuard ]
      },
      {
        path: 'contacts',
        component: ClientContactComponent,
        resolve: { PersonContacts: ClientContactsResolver},
        canDeactivate: [ ClientContactsGuard ]
      },
      {
        path: '',
        redirectTo: 'demographics',
        pathMatch: 'full'
      }
    ]
  },

在这里使用服务。像这样。

HeaderDataService

private pHeaderData: Subject<any> = new Subject<any>();

get headerData(): Observable<any> | any {
    return this.pHeaderData.asObservable();
}

set headerData(data: any) {
    this.pHeaderData.next(data);
}

父组件

const subscription: Subscription = new Subscription();

constructor(private headerDataService: HeaderDataService) { }

ngOnInit(): void {
    this.subscription.add(
        this.headerDataService.headerData.subscribe( data => {
            console.log('delivery from ChildComponent arrived: ', data);
        })
    );
}

ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

子组件

constructor(private headerDataService: HeaderDataService) { }

if (model.dirty && model.valid) {
  // call the saving service
  this.clientService.UpdateClientIdentInfo(personId, model.getRawValue()).subscribe(updatedHeaderData => {

    // inform the parent
    this.headerDataService.headerData = updatedHeaderData;

    this.snackBar.open('Data has been saved successfully!', '', {
      duration: 2000,
      horizontalPosition: 'center',
      verticalPosition: 'bottom',
      panelClass: ['snack-success']
    });
    return true;
  }, error => {
    return false;
  })
}