【发布时间】: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;
});
}
}
【问题讨论】: