簡體   English   中英

in Angular 13、如何通過依賴解析調用內部子組件到父組件? 刷新網格數據的最佳方法是什么?

[英]in Angular 13, How can i call inner child component to parent component with dependency resolve ? what is the best approach to refresh grid data?

我有 UserViewComponent,在我通過調用 openSelectUserModal() 打開模式后,SelectUserComponent 將打開。 然后在這里我必須打開另一個模式,即 AddUserComponent。 打開AddUserComponent后,這里有一個方法addUser()。 在這里我需要使用依賴解析來調用 UserViewComponent.ngOnInit()。 如何以有效的方式做到這一點???

rows:any[];
columns: any[]
page: IPagination;



export class UserViewComponent {
    constructor(private userService: UserService, private alertService: AlertService)
    ngOnInit() {
        this.projectId = this.route.snapshot.paramMap.get('projectId');
        this.loadCommonService();
        this.loadTableSetting();
        this.getUsers();
    }

    getUsers() {
        this.userService.getUsers(this.page, this.projectId).subscribe({
            next: res => {
                this.loadViewData(res);
            }
        });
    }

    loadViewData(result: PaginatedViewModel) {
        this.columns = [];
        this.rows = [];
        this.page.count = result.count;
        this.page.pageNo = result.pageNo;
        this.page.pageSize = result.pageSize;

        this.generatePropertyColumns(result.columns);
        this.generatePropertyRows(result);
        this.loadTableSetting();
    }

    openSelectUserModal() {
        this.modalService.Open<SelectUserComponent>()
    }
}

export class SelectUserComponent(){
    openAddUserModal(){
        this.modalService.Open<AddUserComponent>()
    }
}

export class AddUserComponent {
    addUser() {
        this.userService.createUser(model).then((res) => {
            let id = res.id;

            // Here I need to call UserViewComponent.ngOnInit()
        })
    }
}

你可以在你的服務中使用 Subject,然后訂閱這個 Subject。

//in your Service
change:Subject<void>=new Subject<void>(); //declare a Subject

//each change you use
this.change.next();

現在在您的 UserViewComponent 中訂閱 userService.change 使用 swithMap 返回 getUser 並使用 startWith 獲取初始值

   getUsers() {
   //not subscribe to this.userService.getUser else "change"
   this.userService.change.pipe(
      //you use startWith to initial value
      startWith(null),    

      //you use switchMap to return the 
      //observable "userService.getUsers()"
      switchMap(_=>this.userService.getUsers(this.page, this.projectId)) 
   )
   .subscribe({
            next: res => {
                this.loadViewData(res);
            }
        });
    }

一個簡單的stackbliz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM