添加新值后无法更新表格

时间:2019-09-04 16:15:01

标签: html angular typescript angular-ui-router

我是angular的新手,我正在尝试插入新值并将其显示在表格中。因此,我有三个组件,一个组件用于列出用户user-list的信息,一个组件用于创建信息原始文件user-form,另一个组件用于呈现这些信息single-user

我的问题是,当我尝试插入新的原始信息时,即使我进行了重定向,表liste也不自我更新或刷新,并且我不知道原因。 可能有人给我任何指示。预先感谢。

User-list.component.ts:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../services/user.service';
import { Subscription, Observable } from 'rxjs';
import { User} from '../model/user.model';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit, OnDestroy {

  constructor(private router: Router, private userService : UserService ) { }

  userSubscription: Subscription;
  users: Observable<User[]>;

  ngOnInit() {
    this.reloadData();
  }

  reloadData(){
   this.userSubscription = this.userService.getResource("/users").subscribe(
      data =>{
        this.users= data;
        console.log(this.users);
      },
      error => { console.log(error);
      }
   ); 
  }

  ngOnDestroy() { this.userSubscription.unsubscribe(); }

}

User-list.component.html:

<div id="page-wrapper">
  <div class="main-page">
    <div class="tables">
        <app-user-form></app-user-form>
        <div class="table-responsive bs-example widget-shadow" data-example- 
           id="contextual-table"> 
             <table class="table table-hover "> 
          <thead> 
                <tr> 
                    <th>#</th> 
                    <th>Name</th>
                    <th>Age</th>
                    <th>Action</th> 
                </tr> 
           </thead>
              <tbody class="body">
              <ng-container *ngFor="let u of users"> 
                  <tr class="active" 
                    app-single-user
                    [IdUser] =  "u.idUser"
                    [NameUser] = "u.nameUser"
                    [AgeUser] = "u.ageUser"
                  > 
                  </tr>
            </ng-container>
          </tbody> 
        </table> 
        </div>
    </div>
  </div>
</div>

User-form-component.ts

@Component({
  selector: 'app-user-form',
  templateUrl: './user-form.component.html',
  styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {

  userForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
              private router: Router, 
              private userService: UserService
              ) { }

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.userForm = this.formBuilder.group({
      nameUser: ['', Validators.required],
      ageUser: ['', Validators.required]
    });
  }

  reInitForm() {
    this.userForm = this.formBuilder.group({
      nameUser: '',
      ageUser: ''
    });
  }

  onSubmit(){
    const formValue = this.userForm.value;
    const newuser = new User(
      formValue['nameUser'],
      formValue['ageUser']
    );
    this.userService.postResource('/users', newUser).subscribe(
      data =>{
        console.log(data)
      },
      error=>{
        console.log(error)
      } 
    );
    this.reInitForm();
    this.router.navigate(['/users']);
  }

}

user-form-component.html:

<div class="table-responsive bs-example widget-shadow" data-example-id="contextual-table">

    <div class="main-page">
    <form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="form-inline">
        <div class="form-group">

            &nbsp;
            <input type="text" class="form-control" id="name"
                   formControlName="nameUser" name="name" required>

          <input type="text" class="form-control" id="age" 
                   formControlName="ageUser" name="age" required>

        </div>
        &nbsp; &nbsp;

        <button type="submit" class="btn btn-success"
            [disabled]="userForm.invalid">Submit</button>
    </form>
    </div>

</div>

我尝试重定向到同一组件this.router.navigate(['/users']);来刷新表的内容,但是它不起作用。 如果有人可以给我一些提示或指示来解决它,我将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

如评论中所述,users的类型应为User[],因为您要为其分配已订阅的值,并且导航到相同的组件不会导致该组件重新呈现。

您可以使用@Output来实现。添加newUser后,您将刷新父组件(user-list.component.ts)中的数据。

user-form-component.ts

@Output() submitted = new EventEmitter<void>();

然后在您的POST API成功后,发出事件

this.userService.postResource('/users', newUser).subscribe(
    data => {
        console.log(data);
        this.submitted.emit();
    },
    error => {
        console.log(error);
    } 
);

在父组件的模板中,您需要将此事件添加到自定义组件中。

user-list.component.html

<app-user-form (submitted)="onSubmit($event)"></app-user-form>

然后在您的父组件中。

user-list.component.html

onSubmit() {
    this.reloadData();
}

有关如何使用@Output的更多信息,请参见docs