【问题标题】:list component update while post new record from other component in angular 7列出组件更新,同时在角度 7 中从其他组件发布新记录
【发布时间】:2019-10-08 07:18:55
【问题描述】:

我正在开发一个 Angular 7 项目。我有两个组件,一个是添加角色和列表角色。这两个组件元素放在其他角色组件中。当我通过添加角色组件添加新记录时,如何在不刷新的情况下在列表角色组件中显示新数据?

非常感谢任何帮助...

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;
    });

  }

}

【问题讨论】:

    标签: angular angular7


    【解决方案1】:

    将角色从父组件传递给子组件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

    在 ts 中你应该从 userService 中获取角色

    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!");
          }
        )};
    };
    
    

    【讨论】:

      【解决方案2】:

      在这种情况下,我会使用异步管道。你可以参考文档here

      你有三个组件,一个父亲(RoleComponent)和两个孩子(ListRoleComponent 和 AddRoleComponent)。

      最好从 AddRoleComponent 向 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});
        }
      

      您可以看出我在模型角色(名称)中添加了一个字段。你可以继续你的逻辑,这只是我重新创建的一个例子

      【讨论】:

      • 我认为在 role.component.ts 中的表单提交后,我得到了空列表。请帮助我?
      • 您能给我们一个更好的解释吗?
      猜你喜欢
      • 2016-07-15
      • 1970-01-01
      • 2023-03-14
      • 2023-01-12
      • 2019-07-15
      • 2020-01-04
      • 2022-01-21
      • 2021-03-25
      • 2021-11-02
      相关资源
      最近更新 更多