I have component called customers-list
where I am displaying all my customers from the API:
customers-list.html
<div *ngFor="let customer of customers">
<p>{{customer.name}</p>
</div>
customers-list.ts
import { Component Input} from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';
@Component({
selector: 'drt-customers-list',
templateUrl: './customers-list.component.html',
styleUrls: ['./customers-list.component.scss'],
})
export class CustomerListComponent {
public customers: ICustomer[] ;
constructor(public customersService: CustomersService,) {}
public async ngOnInit(): Promise<void> {
this.customers = await this.customersService.getCustomersList('');
}
}
I have another component called add-customer
, where I will add new customer like this:
public onaddCustomer(): void {
this.someCustomer = this.addCustomerForm.value;
this.customersService.addCustomer( this.someCustomer).subscribe(
() => { // If POST is success
this.successMessage();
},
(error) => { // If POST is failed
this.failureMessage();
}
);
}
Now POST
operation happens fine, but the customer-list
is not updated without refreshing the page.
How can I update the customers-list
component after successful POST
operation, without refreshing the whole page?
services file:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class CustomersService {
private baseUrl : string = '....api URL....';
public async getCustomersList(): Promise<ICustomer[]> {
const apiUrl: string = `${this.baseUrl}/customers`;
return this.http.get<ICustomer[]>(apiUrl).toPromise();
}
public addCustomer(customer: ICustomer): Observable<object> {
const apiUrl: string = `${this.baseUrl}/customers`;
return this.http.post(apiUrl, customer);
}
}