typescript 在其他子组件更改时刷新子组件

yhuiod9q  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(223)

我有两个从父组件调用的子组件:

    • 超文本标记语言**
<app-profile-form [profile]="profile"></app-profile-form>
<app-profile-activity-list [profile]="profile"></app-profile-activity-list>

这一做法运作良好;现在,在第二个组件中,我有一个活动日志列表,如下所示:

    • 超文本标记语言**
<app-datatable 
          [headers]="['#', 'New value','Old value','Description']" [dataLength]="datalength"
          [data]="profileActivities"
           emptyTableMessage="No logs created">

           <tr body *ngFor="let profileActivity of profileActivities; index as i">
            <td scope="row">{{ i + 1 }}</td>
            <td>{{profileActivity.newValue}}</td>
            <td>{{profileActivity.oldValue}}</td>
            <td>{{profileActivity.description}}</td>
           </tr>
           </app-datatable>
    • TS:**
export class ProfileActivityListComponent implements OnInit {
  @Input() profile: ProfileModel;
   profileActivities: ProfileActivity[];

    constructor(
        public apiService: ApiService,
      ) { }
    
      ngOnInit() {
    
        let profileActivityRequestModel = {
            profileId:  this.profile.id,
            ...this.pagination
        }
        this.profileRequest =  profileActivityRequestModel;
    
    
        this.apiService.profileActivityService.getPagedFilteredList(this.profileRequest).subscribe((result) => {
            this.profileActivities = result.resourceModel;
            this.datalength = this.profileActivities.length;
            let totalPages = result.total ? Math.ceil(result.total / result.limit) : 1;
            this.pagination = {
              ...this.pagination,
              total: result.total,
              totalPages: totalPages,
              page: result.offset + 1
            }
          });
      }

最后,在第一个子模型中,我有一个表单,在一天的最后一天,调用API并返回如下响应:

    • 技术支助**
submitForm() {
     this.store.dispatch(new ProfileActions.AddProfile(newProfile));
   }

最后一次调用API在数据库中插入了第二个子组件应该检索的数据。但是直到我刷新页面才反映出更改。是否有方法在第一个组件提交后刷新第二个组件表信息?

    • 更新**this.store.dispatch(new ProfileActions.AddProfile(newProfile));执行动作、效果和还原器为:
    • 行动**
export enum ProfileActionTypes {
ADD_PROFILE = '[PROFILES] Add PROFILE'
}
    export class AddProfile implements Action {
      readonly type = ProfileActionTypes.ADD_PROFILE;
      constructor(public payload: ProfileModel) {
      }
    }
    • 效果:**
@Effect() addNewProfile$ = this.actions$
    .pipe(ofType<AddProfile>(ProfileActionTypes.ADD_PROFILE),
      mergeMap((data) => this.profileService.addProfile(data.payload).pipe(map(result => {
        if (data.payload.status === 3) {
          this.toast.success('Profile DELETED', 'Success');
          return new DeleteProfileSuccess(result);
        }
        if (data.payload.id > 0) {
          this.toast.success(`${result.firstName} ${result.lastName} Profile UPDATED`, 'Success');
        } else {
          this.toast.success(`${result.firstName} ${result.lastName} Profile ADDED`, 'Success');
        }
        return new AddProfileSuccess(result);
      }))));
    • 减速器**
export function profilesReducer(state = initialState, action: ProfilesActions) {

 case ProfileActionTypes.ADD_PROFILE:
      return {
        ...state
      };
}
iibxawm4

iibxawm41#

你可以通过使用@Output()事件发射器和@Viewchild()装饰器来实现它,请按照以下步骤操作
将@Output()事件发射器定义到app-profile-form.component.ts文件中,如下所示

@Output() public dataSaved = new EventEmitter<boolean>();

/* Emit an event when data is get saved, from your profile-form component as below */
 submitForm() {
     this.store.dispatch(new ProfileActions.AddProfile(newProfile));
     setTimeout({
         this.dataSaved.emit(true);
     }, 100);
 }

将事件绑定到父组件中,并将引用添加到视图子组件的配置文件-活动-组件选择器中

<app-profile-form [profile]="profile" (dataSaved)="refreshActivityList($event)"></app-profile-form>
<app-profile-activity-list [profile]="profile" #refProfileActivity></app-profile-activity-list>

在父组件中定义**refreshActivityList()**方法,并为配置文件活动组件创建@viewChild(

@ViewChild('refProfileActivity') refProfileActivity: ProfileActivityListComponent;

public refreshActivityList(event) {
  if (event) {
    this.refProfileActivity.getList();
  }
}

最后但并非最不重要的是,将您的API调用从ngOnInit()钩子移动到任何特定函数ProfileActivityListComponent TS文件中,如下所示

export class ProfileActivityListComponent implements OnInit {
  @Input() profile: ProfileModel;
  profileActivities: ProfileActivity[];

  constructor(public apiService: ApiService) {}

  ngOnInit() {
    this.getList();
  }

  public getList() {
    let profileActivityRequestModel = {
      profileId: this.profile.id,
      ...this.pagination,
    };
    this.profileRequest = profileActivityRequestModel;

    this.apiService.profileActivityService
      .getPagedFilteredList(this.profileRequest)
      .subscribe((result) => {
        this.profileActivities = result.resourceModel;
        this.datalength = this.profileActivities.length;
        let totalPages = result.total
          ? Math.ceil(result.total / result.limit)
          : 1;
        this.pagination = {
          ...this.pagination,
          total: result.total,
          totalPages: totalPages,
          page: result.offset + 1,
        };
      });
  }
}

谢谢!

相关问题