我试图在我的nativescript应用上执行http请求,但是当调用http.get()时,我什么也没有得到,没有错误,也没有对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/'
);
}
}
答案 0 :(得分:2)
您正在创建请求,但从未订阅!您在这里有一些选择:
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
管道(注意!每次显示此屏幕时,它将调用您的api,并且将多次调用async
))< / li>
<Label [text]="servico.text" *ngFor="let servico of servicos | async"></Label>
上下文:
HttpClient
请求始终从Observable
返回rxjs
。
可观察对象是冷对象,这意味着它们只有在有人subscribe
对其执行之后才执行任何代码。相反,Promise
总是在声明时执行。
考虑代码:
const request = new Promise((resolve, reject) => {
console.log("executing");
resolve();
});
setTimeout(() => request.then(() => console.log("success")), 1000)
结果
executing
- 1s wait -
success
现在使用Observable
:
const request = new Observable((subscriber) => {
console.log("executing");
subscriber.next();
subscriber.complete();
});
setTimeout(() => request.subscribe(() => console.log("success")), 1000)
结果:
- 1s wait -
executing
success
async
管道本质上在“呈现”时调用subscribe
,在销毁时unsubscribe
调用,因此您不必自己进行管理。