I have a news where I show a title and a description. it happens that this takes the db and shows it. when I delete or add a content I have to change the route to be able to appreciate the change if I add or modify news from the db directly. Any idea how to update visually too ?
Service
export class NoticiasService {
constructor(private http:HttpClient) {}
headers: HttpHeaders = new HttpHeaders({
"Content-Type": "application/json"
});
mostrarnoticias() {
const url_api = "http://localhost/apixeoms/mostrarnoticias.php";
return this.http.get(url_api);
}
}
TS component
export class NoticiasComponent implements OnInit {
noticia=null;
constructor(private http:NoticiasService) { }
ngOnInit() {
this.obtenernoticias()
}
obtenernoticias() {
this.http.mostrarnoticias().subscribe(
data => this.noticia=data
);
}
}
Html Component
<div class="container" style="background:blue;" *ngFor="let noticia of noticia">
<div class="row">
<div class="col-md-12" >
<p style="text-align:center;">{{noticia.titulo}}</p>
<p>{{noticia.contenido}}</p>
</div>
</div>
</div>
Here I did it with the help you gave me in angular 7
import { Component, OnInit } from '@angular/core';
import {NoticiasService} from '../service/noticias.service';
import { Observable } from "rxjs/internal/Observable";
import { interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import {map} from 'rxjs/operators';
@Component({
selector: 'app-noticias',
templateUrl: './noticias.component.html',
styleUrls: ['./noticias.component.css']
})
export class NoticiasComponent implements OnInit {
noticias$: Observable<any>;
constructor(private http: NoticiasService) { }
ngOnInit() {
this.noticias$ = interval(1000).pipe(
switchMap(() => this.http.mostrarnoticias()))
}
}
Could you more or less explain to me what the pipe and the switchMap do?
you have three options:
1) Async Pipe & Observables
In this case you must create an observable type variable that makes constant requests to your backend
in your template apply the pipe async
2) Sockets
Here you must modify your backend and implement a library that allows handling sockets, socket.io is currently widely used.
3) Firebase
A quick solution is to use firebase, it's fast and doesn't need much configuration, as for the angular client you don't have to do anything.