I'm currently facing an issue where my component does not refresh the UI after I input data. I always have to manually refresh the page to see the changes. I suspect there might be a problem with the .subscribe method in Angular 6. Previously, when I was using a pure Angular 2 environment, it worked fine.
Below is my component:
ngOnInit() {
this.company = [];
this.inputCompanyService.getAllCompany().subscribe(company => {
this.company = company;
});
}
postCompany(event, companyName, ) {
var result;
var newCompany = {
company_name: companyName.value,
id: companyName.id
};
result = this.inputCompanyService.postCompany(newCompany);
result.subscribe(x => {
this.company.push(newCompany);
companyName.value = '';
});
}
This is my service:
getAllCompany() {
return this._http.get('http://localhost:3000/api/companys')
.map(res => res.json());
}
postCompany(company_name) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this._http.post('http://localhost:3000/api/company', JSON.stringify(company_name), { headers: headers })
.map(res => res.json());
}
Here's the HTML code:
<div class="input-company">
<p>
<mat-form-field appearance="legacy">
<input matInput [(ngModel)]="companyName.company_name" placeholder="Here..." autofocus #companyName>
<!-- <mat-icon matSuffix>sentiment_very_satisfied</mat-icon> -->
</mat-form-field>
<button mat-raised-button color="warn" (click)="postCompany($event, companyName)">Click me !</button>
</p>
<div *ngFor="let company of company.company">
<li>
<button mat-flat-button (click)="deleteCompany(company)">X</button>
<button mat-flat-button>N</button>
<button mat-stroked-button>{{company.id}}-{{company.company_name}}</button>
</li>
</div>
</div>