Angular 7 - Reload / refresh data different compon

2019-08-13 00:08发布

问题:

How to refresh data in different component 1 when changes made in component 2. These two components are not under same parentnode.

customer.service.ts

export class UserManagementService extends RestService {

  private BASE_URL_UM: string = '/portal/admin';

  private headers = new HttpHeaders({
    'Authorization': localStorage.getItem('token'),
    'Content-Type': 'application/json'
  });

  constructor(protected injector: Injector,
    protected httpClient: HttpClient) {
    super(injector);
  }
  getEapGroupList(): Observable < EapGroupInterface > {
    return this.get < GroupInterface >
      (this.getFullUrl(`${this.BASE_URL_UM}/groups`), {
        headers: this.headers
      });
  }

  updateGroup(body: CreateGroupPayload): Observable < CreateGroupPayload > {
    return this.put < GroupPayload >
      (this.getFullUrl(`${this.BASE_URL_UM}/group`), body, {
        headers: this.headers
      });
  }
}

Component1.ts

export class UserGroupComponent implements OnInit {

  constructor(private userManagementService: UserManagementService) {}

  ngOnInit() {
    this.loadGroup();
  }

  loadGroup() {
    this.userManagementService.getEapGroupList()
      .subscribe(response => {
        this.groups = response;
      })
  }

}
<mat-list-item *ngFor="let group of groups?.groupList" role="listitem">
  <div matLine [routerLink]="['/portal/user-management/group', group.groupCode, 'overview']" [routerLinkActive]="['is-active']">
    {{group.groupName}}
  </div>
</mat-list-item>
<mat-sidenav-content>
  <router-outlet></router-outlet>
</mat-sidenav-content>

component2.ts

setPayload() {
  const formValue = this.newGroupForm.value
  return {
    'id': '5c47b24918a17c0001aa7df4',
    'groupName': formValue.groupName,
  }
}

onUpdateGroup() {
    this.userManagementService.updateGroup(this.setPayload())
      .subscribe(() => {
          console.log('success);
          })
      }

When I update onUpdateGroup() api in component1, loadGroup() should refresh in component2

回答1:

Move the code that retrieves the data to the service so the service maintains the groups.

Then wrap that data in Component 1 in a getter:

get groups() {
  return this.userManagementService.groups
}

Then each time that the data changes, Angular's dependency injection will automatically call the getter and get the most recent values.

Revised service

export class UserManagementService extends RestService {
  groups;
  private BASE_URL_UM: string = '/portal/admin';

  private headers = new HttpHeaders({
    'Authorization': localStorage.getItem('token'),
    'Content-Type': 'application/json'
  });

  constructor(protected injector: Injector,
    protected httpClient: HttpClient) {
    super(injector);

    // Get the data here in the service
    this.loadGroup();
  }

  getEapGroupList(): Observable < EapGroupInterface > {
    return this.get < GroupInterface >
      (this.getFullUrl(`${this.BASE_URL_UM}/groups`), {
        headers: this.headers
      });
  }

  loadGroup() {
    this.getEapGroupList()
      .subscribe(response => {
        this.groups = response;
      })
  }

  updateGroup(body: CreateGroupPayload): Observable < CreateGroupPayload > {
    return this.put < GroupPayload >
      (this.getFullUrl(`${this.BASE_URL_UM}/group`), body, {
        headers: this.headers
      }).pipe(
         // Reget the data after the update
         tap(() => this.loadGroup()
      );
  }
}

Revised component 1

export class UserGroupComponent implements OnInit {
    get groups() {
      return this.userManagementService.groups
    }

  constructor(private userManagementService: UserManagementService) {}

  ngOnInit() {

  }
}

NOTE: This code was not syntax checked!

I have a similar working example here: https://github.com/DeborahK/Angular-Communication/tree/master/APM-FinalWithGetters

(Check out the product-shell folder files along with the product.service.ts)



回答2:

Create an @Injectable service class with a Subject in it. Have both components look at this service class subject to see what to do when. One class can call .next() on the subject and the other can subscribe to it and call it's own function when it gets an update.



回答3:

There is a lot of example on the web, you can use "Subject" and Output EventEmitter. Both will work. The following example is the sample code of shared service. Try to use it.

@Injectable()
export class TodosService {
  private _toggle = new Subject();
  toggle$ = this._toggle.asObservable();

  toggle(todo) {
    this._toggle.next(todo);
  }
}

export class TodoComponent {
  constructor(private todosService: TodosService) {}

  toggle(todo) {
    this.todosService.toggle(todo);
  }
}

export class TodosPageComponent {
  constructor(private todosService: TodosService) {
    todosService.toggle$.subscribe(..);
  }
}


回答4:

Write a common service and call the same in both components.
like below:

common service: 
           dataReferesh = new Subject<string>();
           refereshUploadFileList(){
            this.dataReferesh.next();
            }

component2.ts:

    setPayload() {
      const formValue = this.newGroupForm.value
      return {
        'id': '5c47b24918a17c0001aa7df4',
        'groupName': formValue.groupName,
      }
    }

        onUpdateGroup() {
         this.userManagementService.updateGroup(this.setPayload())
           .subscribe(() => {
             this.shareservice.refereshUploadFileList(); 
               })
           }

And component1.ts:


         ngOnInit() {
         this.loadGroup();
         this.shareservice.dataReferesh.subscribe(selectedIndex=> this.loadGroup());
          }