Search code examples
angularasynchronousobservablerefreshreal-time

Angular refresh data automatically


Im trying to make an admin panel where the user can see the bookings for his restaurant in real time. The idea is for new bookings to automatically show in the bookings component, without needing to refresh the page. Im using the async pipe, and it shows all the bookings on the db, but wont automatically refresh.

THIS IS THE BOOKING SERVICE

@Injectable()

export class BookingService{

    public url:string;
    public booking:Booking;

        constructor(
            private _http: HttpClient
            ){
            this.url= global.url;
        }

makeBooking(booking){

    let headers= new HttpHeaders().set('Content-type','application/x-www-form-urlencoded'); 

    let json= JSON.stringify(booking);

    let params='json='+json;

    return this._http.post(this.url+ 'booking',params, {headers:headers});
}

getBookings():Observable<any>{
    let headers= new HttpHeaders().set('Content-type','application/x-www-form-urlencoded'); 

    return  this._http.get(this.url+ 'booking/0',{headers:headers});
}

And now the component

@Component({
  selector: 'app-turnos',
  templateUrl: './bookings.component.html',
  styleUrls: ['./bookings.component.css'],
  providers:[BookingService]
})
export class BookingsComponent implements OnInit {

    public bookings;
    public status;
    public bookings$: Observable<any>;

  constructor(

    private _bookingService: BookingService

    ) {}

  ngOnInit(): void {


       this.bookings$=this._bookingService.getBookings().pipe(map(res=>this.bookings=res.bookings));
    }


}

Finally, on the template im using

<tr *ngFor="let booking of (bookings$ | async) ">
      <th scope="row">{{booking.id}}</th>
      <td>{{booking.user_name}}</td>
       etc 
       etc
 </tr>

Solution

  • You are currently sending a single HTTP GET request in order to retrieve the bookings, which does retrieve the current bookings. In order to get bookings updates you have multiple options:

    HTTP Polling: Send a new HTTP request every while, e.g. every 5 seconds to get updates. Here's a quick tutorial for angular & rxjs

    Server-Sent Events (SSE): Sends a single request and keeps the HTTP Connection open, and get updates on realtime from server only (server-to-client communication). Here's a quick tutorial for Angular + NodeJs

    I would use SSE to limit the calls to the server. There is another popular choice, which is using WebSockets, they work the same as SSE but allow for client-to-server communication as well, they are mainly used for realtime chat.