Таблица материалов не обновляет данные после вставки - PullRequest
0 голосов
/ 15 января 2020

Я получил данные компонента, содержащие таблицу материалов, и другую, которая содержит компонент формы. При первом запуске приложение перечисляет все элементы правильно, но после вставки таблица не обновляется автоматически только при обновлении страницы. Данные получены из person.service

My Form.component.ts:

import { Component, OnInit, EventEmitter, Output, ViewChild, AfterViewInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { Person } from '../person/person.model';
import { MatSnackBar, MatTableDataSource } from '@angular/material';
import { PersonService } from '../person/person.service';
import { DataComponent } from '../tableData/data.component';



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

  @Output() addedPerson = new EventEmitter<any>();

  @ViewChild(DataComponent, { static: false }) dataComponent: DataComponent;

  newPerson: Person = new Person();
  // editedPerson: Person;


  nameFormControl = new FormControl('', [Validators.required]);
  lastNameFormControl = new FormControl('', [Validators.required]);
  emailFormControl = new FormControl('', [Validators.required, Validators.email]);
  phoneFormControl = new FormControl('', [Validators.required]);



  constructor(public snackbar: MatSnackBar, private personService: PersonService) { }

  ngOnInit() {
  }

  ngAfterViewInit() { }

  savePerson() {
    this.personService.addPerson(this.newPerson).subscribe(response => {
      this.snackbar.open('Usuario Agregado', null, { duration: 2000 });
      this.clear();
      this.personService.getPersonsList().subscribe(list => {
        this.dataComponent.dataSource = list;
      });
    });
  }

  // CLEAR ALL INPUTS
  clear() {
    this.newPerson.name = '';
    this.nameFormControl.clearValidators();
    this.newPerson.lastName = '';
    this.lastNameFormControl.clearValidators();
    this.newPerson.email = '';
    this.emailFormControl.clearValidators();
    this.newPerson.phone = '';
    this.phoneFormControl.clearValidators();
  }
}

My data.component.ts

import { Component, OnInit, ViewChild, Input, Output, EventEmitter } from '@angular/core';
import { Person } from '../person/person.model';
import { PersonService } from '../person/person.service';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
  dataSource;
  // displayedColumns: string[] = ['Id', 'nombre', 'apellido', 'email', 'telefono', 'acciones'];
  displayedColumns: string[] = ['nombre', 'apellido', 'email', 'telefono', 'acciones'];
  @ViewChild('dataTable', { static: false }) dataTable;
  // @Output() sendDataBack = new EventEmitter<{ index, name, lastName, email, phone }>();

  constructor(private personService: PersonService) { }

  ngOnInit() {
    this.personService.getPersonsList().subscribe(
      personsList => {
        this.dataSource = personsList;
        console.log(personsList);
      });
  }

  editPerson(element) {
    // this.sendDataBack.emit({
    //   index: this.dataSource.indexOf(element),
    //   name: element.name, lastName: element.lastName, email: element.email, phone: element.phone
    // });
  }

  deletePerson(element) {
    // this.dataSource.splice(element.index, 1);
    // this.dataTable.renderRows();
  }

}

My person.service. ts

import { Injectable } from '@angular/core';
import { Person } from './person.model';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Subject } from 'rxjs';

@Injectable()
export class PersonService {

  private url = 'http://localhost:8080/persons';
  private httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });

  constructor(private http: HttpClient) { }

  getPersonsList(): Observable<Person[]> {
    return this.http.get<Person[]>(this.url);
  }

  addPerson(person: Person): Observable<Person> {
    return this.http.post<Person>(this.url, person, { headers: this.httpHeaders });
  }

}

Я все еще учусь angular, поэтому я не знаю, что мне не хватает. Заранее спасибо

1 Ответ

0 голосов
/ 16 января 2020

Итак, я нашел способ сделать это, просто позвонив

this.dataComponent.dataTable.dataSource = this.personService.getPersonsList();

После отправки генератора событий в app.component.

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