I'm currently working on an app with Angular CLI, and I am trying to retrieve a list after an insertion. Despite trying various methods such as observer, promise, async, setTimeout, etc., I haven't been able to find the right solution yet. I feel like I might be close, but something is missing.
Below is the code I have so far. In the insertStatut() function, I perform the insertion (service.insertStatuts()) and then immediately call getStatuts() to update the list.
Here is the code in my component :
import { Component, OnInit } from '@angular/core';
import { MatStatutService } from '../mat-statut.service';
import { MatStatut } from '../matStatut';
@Component({
selector: 'app-mat-statut',
templateUrl: './mat-statut.component.html',
styleUrls: ['./mat-statut.component.css']
})
export class MatStatutComponent implements OnInit {
private statuts: MatStatut[];
private inStatut = new MatStatut;
constructor(private service:MatStatutService) {
}
// get statuts at launch
ngOnInit() {
this.getStatuts();
}
// get list of statuts
public getStatuts(): void{
this.service.getStatuts().subscribe(posts => this.statuts = posts);
console.log(this.statuts);
}
// insert a new statut
public insertStatut():void{
this.inStatut.setLibelle('Test');
// insert new statut
this.service.insertStatut(this.inStatut);
// refresh list of statuts
this.getStatuts();
// reset insertion Statut
this.resetMatStatut(this.inStatut);
}
// reset statut
public resetMatStatut(statut: MatStatut){
statut.resetData();
}
}
And here is the code in my service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatStatut } from './matStatut';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MatStatutService {
constructor(private http: HttpClient) {}
getStatuts(): Observable<MatStatut[]>{
return this.http.get<MatStatut[]>('http://localhost/rest/fonctions/matStatut/getAll.php');
}
insertStatut(statut: MatStatut) {
this.http.post('http://localhost/rest/fonctions/matStatut/create.php', {
mat_statut_libelle: statut.getLibelle()})
.subscribe(
res => {
console.log(res);
},
err =>{
console.log(err);
});
}
}
I hope my explanations are clear enough, and please forgive any mistakes in my English.