Angular 7-重新加载/刷新不同组件的数据 [英] Angular 7 - Reload / refresh data different components
本文介绍了Angular 7-重新加载/刷新不同组件的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在组件2中进行更改时,如何刷新不同组件1中的数据.这两个组件不在同一父节点下.
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);
})
}
当我在 component1 中更新onUpdateGroup()api时,loadGroup()应该在 component2
When I update onUpdateGroup() api in component1, loadGroup() should refresh in component2
推荐答案
网络上有很多示例,您可以使用主题"和Output EventEmitter.两者都会起作用.下面的示例是共享服务的示例代码.尝试使用它.
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(..);
}
}
这篇关于Angular 7-重新加载/刷新不同组件的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文