Angular список предметов не обновляется при изменении в Сервисе - PullRequest
0 голосов
/ 13 января 2020

У меня есть два компонента: один родительский, который содержит форму для добавления файла, и другой дочерний элемент, который показывает список добавленных элементов (файлов), я хочу обновить свою таблицу элементов после добавления одного, я подписан, но не обнаруживает изменения, когда его добавление (извините за мой плохой engli sh), вот мой код: this.dataSource = resp.files; не обновляется снова, только один раз в первый раз .

решено!

files.component.ts

    export class FilesComponent implements OnInit {
      dataSource;
      columnsToDisplay = ['name', 'year', 'created_at', '_id'];
      expandedElement: File | null;
      constructor(
        public _file: FileService
      ) {}

      ngOnInit() {
        this._file.$files.subscribe((resp: any) => {
          this._file.getFiles();  //*******PARTIALLY SOLVED i call getFiles() inside but
                                  // Now constantly call getFiles()  :/
          this.dataSource = resp.files;
        });
      }
    }

add-file.component.ts

    send() {
    const newFile = {
      name: this.name,
      status: 'activo',
      year: this.yearCtrl.value,
      from_id: this.selectedFrom._id,
      career_id: this.selectedCareer
    };
    this._file.newFile(newFile).subscribe( (resp: any) => {
      // this._file.getFiles();  //*******Removed
      console.log(resp);
      }
    }, err => {
      console.log(err);
    };

Service.ts

    @Injectable({
      providedIn: 'root'
    })
    export class FileService {
      private headers;
      public URL = URL;
      private files = new BehaviorSubject<any>([]);
      public $files = this.files.asObservable();

      constructor(
        private _http: HttpClient
      ) {
        this.headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        // this.getFiles();  //*******Removed
      }

      getFiles(id: String = null) {
         this._http.get(URL + '/file', { headers: this.headers }).subscribe( (resp: any) => {
          return this.files.next(resp);
        });
      }

      newFile( newFile: any) {
        console.log(newFile);
        return this._http.post(this.URL + '/file', newFile, { headers: this.headers }).subscribe( (resp: any) => {
          this.getFiles(); 
        });
      }
    }

Я использую angular таблицу материалов, но мой component.ts не читает изменения в сервисе var. я буду признателен за помощь !!

1 Ответ

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

Я решил свою проблему, вызвав child метод getFile () из parent при создании файла, используя Subject для получения уведомлений при каждой отправке нового файла.

Родительский компонент.ts

send() {
    const newFile = {
      name: this.name,
      status: 'activo',
      year: this.yearCtrl.value,
      from_id: this.selectedFrom._id,
      career_id: this.selectedCareer
    };
    this._file.newFile(newFile).subscribe( (resp: any) => {
      this.reloadFiles.next(true);
    });
  };

Родитель HTML


    <app-files [reload]="reloadFiles" [file]="searchFilter"></app-files>

Дочерний компонент.ts

@Input() reload: Subject<boolean>;

ngOnInit() {
    this.getFiles();
    this.reload.subscribe(v => {
      this.getFiles();
    });
  } 

getFiles() {
    this._file.getFiles().subscribe( (resp: any ) => {
       this.dataSource = new MatTableDataSource(resp.files);
    });
}

Service.ts

getFiles(id: String = null) {
    return this._http.get(URL + '/file', { headers: this.headers });
  }

Я не знаю, правильно ли это, но работает нормально! Thx

...