You are creating the request, but never subscribing to it! You have a few options here:
- Subscribe manually and update
servicos
private servicos: Servico[];
constructor(
private servicosService: ServicosService
) {
// Use the component constructor to inject providers.
this.servicos = this.servicosService.listar().subscribe((response) => this.servicos = response);
}
- Keep the same code, but use
async pipes in your html (be careful! it'll call your api every time this screen shows, and will call multiple times for multile asyncs)
<Label [text]="servico.text" *ngFor="let servico of servicos | async"></Label>
Context:
HttpClient requests always return Observable from rxjs.
Observables are cold objects, meaning they do not execute any code until someone subscribes to it. In contrast, Promises always execute at the time it is declared.
Consider the code:
const request = new Promise((resolve, reject) => {
console.log("executing");
resolve();
});
setTimeout(() => request.then(() => console.log("success")), 1000)
Results in
executing
- 1s wait -
success
Now using Observable:
const request = new Observable((subscriber) => {
console.log("executing");
subscriber.next();
subscriber.complete();
});
setTimeout(() => request.subscribe(() => console.log("success")), 1000)
Results in:
- 1s wait -
executing
success
The async pipe essentially calls subscribe when it's "rendered" and unsubscribe when destroyed, so you don't have to manage it yourself.