Reputation: 13
I'm trying to perform http requests on my nativescript app, but when call http.get(), I get nothing, no error, no calls into the api.
servicos.component.ts
private servicos: Observable<Servico[]>;
constructor(
private servicosService: ServicosService
) {
// Use the component constructor to inject providers.
this.servicos = this.servicosService.listar();
}
ngOnInit(): void {
// Init your component properties here.
}
servicos.service.ts
@Injectable()
export class ServicosService{
constructor(private http: HttpClient){
}
listar(){
return this.http.get<any>(
CONSTANTS.SERVER_URL + '/servicos/'
);
}
}
Upvotes: 0
Views: 294
Reputation: 341
You are creating the request, but never subscribing to it! You have a few options here:
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);
}
async
pipes in your html (be careful! it'll call your api every time this screen shows, and will call multiple times for multile async
s)<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 subscribe
s to it. In contrast, Promise
s 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.
Upvotes: 2