【问题标题】:How to make http GET/POST request in ionic 2?如何在 ionic 2 中发出 http GET/POST 请求?
【发布时间】:2022-03-05 18:02:25
【问题描述】:

如何在 ionic2 中 http GET/POST 请求 需要导入哪些数据?
我尝试使用HTTP GET request in JavaScript?,但它对我不起作用。

【问题讨论】:

    标签: ionic-framework ionic2


    【解决方案1】:

    GET 示例

    this.posts = null;
    
    this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot').map(res => res.json()).subscribe(data => {
        this.posts = data.data.children;
    });
    
    console.log(this.posts);
    

    https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

    POST 示例

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    
    let body = { 
      message:"do you hear me?"
    };
    
    this.http.post('http://spstest.000webhostap..., JSON.stringify(body), {headers: headers})
     .map(res => res.json())
     .subscribe(data => {
       console.log(data);
      });
    }
    

    https://www.joshmorony.com/how-to-send-data-with-post-requests-in-ionic-2/

    祝你好运。

    【讨论】:

    • 是否可以将数据分配给本地对象,以便我可以将数据中的值显示到 html 页面
    【解决方案2】:

    为了首先创建请求,我们需要使用此命令添加提供者:-

    $ ionic g provider restService
    

    这里 restServicets 文件名,我们在其中编写以下代码以发出请求

       load() {
    
        console.log(' RestServiceProvider Load Method fro listing');
        let postParams = { param1 : '', param2: '' }
        if (this.data) {
          return Promise.resolve(this.data);
        }
    
        // don't have the data yet
        return new Promise(resolve => {
          this.http.post("YOUR URL", postParams)
            .map(res => res.json())
            .subscribe(data => {
              this.data = data;
              resolve(this.data);
            });
        });
      }
    

    在上面的代码中 load() 是 restService 类的方法。这个方法是帮助发出请求的。这个方法在你的其他类中调用是这样的。

     this.restSrvProvider.load().then(data => {
           let mydata = data;
          });
    

    更多知识大家可以去ionic blog这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2012-06-28
      • 1970-01-01
      相关资源
      最近更新 更多