带有角度的本机脚本不执行Http请求

时间:2019-06-12 00:35:53

标签: nativescript nativescript-angular

我试图在我的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/'
        );
    }
}

1 个答案:

答案 0 :(得分:2)

您正在创建请求,但从未订阅!您在这里有一些选择:

  1. 手动订阅并更新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);

    }
  1. 保留相同的代码,但在HTML中使用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调用,因此您不必自己进行管理。