首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在angular 7中从其他组件发布新记录时列表组件更新

在angular 7中从其他组件发布新记录时列表组件更新
EN

Stack Overflow用户
提问于 2019-05-22 04:38:46
回答 2查看 45关注 0票数 0

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

任何帮助都非常感谢...

role.component.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
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

代码语言:javascript
复制
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;
    });

  }

}
EN

回答 2

Stack Overflow用户

发布于 2019-05-22 05:08:54

将角色从父组件传递给子list-role

角色组件HTML

代码语言:javascript
复制
<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获取角色

代码语言:javascript
复制
roles = [];

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

list-role.component.ts

承担角色并与其他角色合并

代码语言:javascript
复制
@Input() set roles(roles: Roles[]) {
  this.roles = merge({}, roles);
};

添加角色

在添加角色中,您可以发出当前创建的角色

代码语言:javascript
复制
@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!");
      }
    )};
};
票数 0
EN

Stack Overflow用户

发布于 2019-05-22 05:59:26

在这种情况下,我将使用异步管道。您可以使用documentation here

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

最好从AddRoleComponent向RoleComponent发出一个事件,警告插入了一个新角色。然后,您可以再次请求角色。我的代码是:

role.component.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
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();
  }

}

列表-(简写)role.Component.html

代码语言:javascript
复制
<div style="color: red" *ngFor="let r of roles">
  {{ r.name }}
</div>

list-role.component.ts

代码语言:javascript
复制
export class ListRoleComponent implements OnInit {

  @Input() roles: Role[];

  constructor() { }

  ngOnInit() {
  }

}

**add-role.component.html (简写) **

代码语言:javascript
复制
<button (click)="onSubmit()">Adicionar</button>

add-role.component.ts

代码语言:javascript
复制
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!");
      }
    );
  }
}

在服务中,方法是:

代码语言:javascript
复制
  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});
  }

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56246025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档