I'm adding my data through ng-bootstrap modal but i have a problem since when i click the add button, it needs to be refresh before i can see the new added data. I already called the this.getMaterials() when i successfully added the product but it still needs to be refreshed before i can see the new added data
export class MaterialsListComponent implements OnInit {
closeResult: string;
materials: any;
subscription: Subscription;
constructor(private modalService: NgbModal, private materialsService: MaterialsService) { }
ngOnInit() {
this.getAllMaterials();
}
getAllMaterials() {
this.subscription = this.materialsService.getAll()
.subscribe(
(data:any) => {
this.materials = data;
console.log(data);
},
error => {
console.log(error);
});
}
onCreateMaterial(form: NgForm){
const name = form.value.name;
const description = form.value.description;
this.materialsService.addMaterial(name, description)
.subscribe(
data => {
this.getAllMaterials();
console.log(data);
},
error => {
console.log(error);
});
}
open(content) {
this.modalService.open(content).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
service
export class MaterialsService {
url = AppSettings;
materials: any;
constructor(private httpClient: HttpClient) {}
getAll() {
if(!this.materials) {
this.materials = this.httpClient.get<any>(this.url)
.map((response => response))
.publishReplay(1)
.refCount();
}
return this.materials;
}
addMaterial(name: string, description: string) {
return this.httpClient
.post(
this.url,
JSON.stringify({ name, description})
)
.map((response: any) => {
return response;
});
}