обновление компонента списка при публикации новой записи из другого компонента в angular 7 - PullRequest
0 голосов
/ 21 мая 2019

Я работаю над проектом Angular 7.У меня есть два компонента, один из них - add-role и list role.эти два компонента помещают в другой компонент роли.Когда я добавляю новую запись через компонент добавления роли, как можно показать новые данные в компоненте роли списка без какого-либо обновления?

Любая помощь очень ценится ...

role.component.html

<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
                <add-role></add-role>
            </div>

            <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
                    <list-role></list-role>
            </div>

add-role.component.ts

import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../_services/users.service';
import { ToastrService } from 'ngx-toastr';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { Role } from '../../_models/Role';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-add-role',
  templateUrl: './add-role.component.html',
  styleUrls: ['./add-role.component.sass']
})
export class AddRoleComponent implements OnInit {
  public roleModel = {};
  roles: Role[] = [];
  constructor(private userService: UsersService, private toastr: ToastrService, private router: Router) { }

  ngOnInit() {

  }

  onSubmit(roleForm: NgForm) {
    this.userService.addRole(this.roleModel).subscribe(
      res => {
        this.toastr.success(res.message, "Success!");
        roleForm.form.reset();
      },
      err => {
        this.toastr.error(err, "oops!");
      }
    )};


}

list-role.component.ts

import { Component, Input, OnInit} from '@angular/core';
import { Role } from '../../_models/Role';
import { UsersService } from '../../_services/users.service';
import { ToastrService } from 'ngx-toastr';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-list-role',
  templateUrl: './list-role.component.html',
  styleUrls: ['./list-role.component.sass']
})
export class ListRoleComponent implements OnInit {
  roles: Role[] = [];
  constructor(private userService: UsersService, private toastr: ToastrService) { }

  ngOnInit() {
    this.getRoles();
  }
  getRoles(){
    this.userService.listroles().pipe(first()).subscribe(roles => {
      this.roles = roles;
    });

  }

}

Ответы [ 2 ]

0 голосов
/ 22 мая 2019

В этом случае я бы использовал асинхронную трубу.Вы можете документацию здесь

У вас есть три компонента: отец (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});
  }

Вы можете сказать, что я добавил одно поле для моей модели Роль (имя).Вы можете продолжить свою логику, это всего лишь пример, который я воссоздал

0 голосов
/ 22 мая 2019

Передача ролей от родительского компонента к дочернему list-role

Компонент ролей HTML

<div class="col-lg-6 col-md-6 col-sm-6 col-xs-
  <add-role (role)="roles.push($event)"></add-role>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-
  <list-role [roles]="roles"></list-role>
</div>

Компонент ролей TS

В этих случаях вы должны брать роли из сервиса пользователя.

roles = [];

getRoles() { 
  this.userService.listroles().pipe(first()).subscribe(roles => {
    this.roles = roles;
  });
}

list-role.component.ts

Берите роли и объединяйтесь с другими

@Input() set roles(roles: Roles[]) {
  this.roles = merge({}, roles);
};

Добавьте роль

В роли добавьте васможет выдать текущую роль, созданную

@Ouput() role: EventEmitter<Role> = new EventEmitter<Role>();


onSubmit(roleForm: NgForm) {
    this.userService.addRole(this.roleModel).subscribe(
      res => {
        this.toastr.success(res.message, "Success!");
        roleForm.form.reset();
        this.role.emit(this.roleModel);
      },
      err => {
        this.toastr.error(err, "oops!");
      }
    )};
};

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...