В этом случае я бы использовал асинхронную трубу.Вы можете документацию здесь
У вас есть три компонента: отец (RoleComponent) и два дочерних элемента (ListRoleComponent и AddRoleComponent).
Лучше всего выпустить событие изДобавьтеRoleComponent к RoleComponent, чтобы предупредить, что была добавлена новая роль.Затем вы можете снова попросить роли.Мой код такой:
role.component.html
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<app-add-role (formSubmited)="onFormSubmited($event)"></app-add-role>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<app-list-role [roles]="(roles | async)?.roles"></app-list-role>
</div>
role.component.ts
export class ProfileComponent implements OnInit {
roles: Observable<Role[]>;
constructor(private userService: UsersService) {
}
ngOnInit() {
this.getRoles();
}
getRoles() {
this.roles = this.userService.listRoles();
}
onFormSubmited(e) {
this.getRoles();
}
}
list-role.component.html (короткая версия)
<div style="color: red" *ngFor="let r of roles">
{{ r.name }}
</div>
list-role.component.ts
export class ListRoleComponent implements OnInit {
@Input() roles: Role[];
constructor() { }
ngOnInit() {
}
}
** add-role.component.html (короткая версия) **
<button (click)="onSubmit()">Adicionar</button>
add-role.component.ts
export class AddRoleComponent implements OnInit {
public roleModel = {
name: 'Nuevo'
};
roles: Role[] = [];
@Output() formSubmited = new EventEmitter<boolean>();
constructor(private userService: UsersService, private router: Router) { }
ngOnInit() {
}
onSubmit(roleForm: NgForm) {
this.userService.addRole(this.roleModel).subscribe(
res => {
// this.toastr.success(res.message, "Success!");
// roleForm.form.reset();
this.formSubmited.emit(true); // important
},
err => {
// this.toastr.error(err, "oops!");
}
);
}
}
В сервисе методявляются:
listroles(): Observable<Role[]> {
return this.http.get<Role[]>(this.url);
}
addRole(roleModel): Observable<any> {
const params = JSON.stringify(roleModel);
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.http.post<Role>(this.url + '/add', params, {headers});
}
Вы можете сказать, что я добавил одно поле для моей модели Роль (имя).Вы можете продолжить свою логику, это всего лишь пример, который я воссоздал