首页 > 解决方案 > 我在 ionic 中使用了 api,但我遇到了一些问题。你能解释一下我们如何在 ionic 中使用 api 吗?

问题描述

    import { Component, OnInit } from '@angular/core';
    import { HTTP } from '@ionic-native/http/ngx';
    @Component({
        selector: 'app-home',
        templateUrl:'./home.page.html',
        styleUrls: ['./home.page.scss'],
        })
    export class HomePage implements OnInit {
        requestObject:any=null; 
        constructor(private http: HTTP) {}
        ngOnInit(){}
        getRequest({
            this.http.get(url:'https://jsonplaceholder.typicode.com/todos/1',
                parameters:{},
                headers:{}
            ).then(onfulfilled:res=>this.requestObject =res.data)
            .catch(onrejected:err=>this.requestObject=err);
}}

标签: c#ionic-framework

解决方案


在您拥有的 getRequest 代码上

getRequest({
        this.http.get(url:'https://jsonplaceholder.typicode.com/todos/1',
            parameters:{},
            headers:{}
        ).then(onfulfilled:res=>this.requestObject =res.data)
        .catch(onrejected:err=>this.requestObject=err);

最后两行:

.then(onfulfilled:res=>this.requestObject =res.data)

.catch(onrejected:err=>this.requestObject=err)

应该意味着(我有一段时间没有接触过角度)如果请求没有错误,则调用onfulfilled,但如果有错误,则调用onrejected

您需要在代码中定义这两个函数,以便 Angular 在适当的时候调用它们。


推荐阅读