首页 > 解决方案 > 如何在上一个 api 请求在 ionic 中完成后发出 api 请求

问题描述

我正在向 wordpress api 发出 3 个 api 发布请求: 2 个 api 发布请求到 wp-json/wp/v2/media 所以上传图像 1 个 api 发布请求到 wp-json/wp/v2/posts 以保存 source_url (这是从之前的 2 个 api 发布请求中检索到)到创建的新帖子。

最后一个 api 依赖于前 2 个 api 请求调用,并且在这 2 个 api 完成之前不应执行,因为我需要它们的回调中的值在我的最后一个 api 请求调用中使用。

我当前的问题是我所有的 api 请求调用都在同时运行,因此前 2 个 api 调用请求中我需要的值尚未准备好,并且它们在我的最后一个 api 请求调用中显示为空。

submitStory() {

    this.beforeImageUpload = this.transfer.create();
    this.beforeImageUpload.upload(this.beforeImageURL, this.url + "wp-json/wp/v2/media", {
      headers: {
        "Authorization": "Basic xxxxxxx",
        "content-disposition": "attachment; filename=\'before-image.jpg\'"
      }
    })
    .then((data)=>{
      return JSON.parse(data.response);
    })
    .then((data) => {
      this.before_image = data.source_url;
    }, (err) => {
      console.log(err);
    })

    this.afterImageUpload = this.transfer.create();
    this.afterImageUpload.upload(this.afterImageURL, this.url + "wp-json/wp/v2/media", {
      headers: {
        "Authorization": "Basic xxxxxxxx",
        "content-disposition": "attachment; filename=\'after-image.jpg\'"
      }
    })
    .then((data)=>{
      return JSON.parse(data.response);
    })
    .then((data) => {
      this.after_image = data.source_url;
    }, (err) => {
      console.log(err);
    })

    let postData = {
      "title": capital_letter(this.firstname + " " + this.lastname + "'s Story"),
      "content": this.description,
      "before_image": this.before_image,
      "after_image": this.after_image
    }

    this.http.post(this.url + "wp-json/wp/v2/stories", postData, {
      headers: {
        "Authorization": "Basic xxxxxxx",
        "Accept": "application/json",
        "Content-Type": "application/json"
      }
    }).subscribe(data => {
      console.log(data);
    }, error => {
      console.log(error);
    });

    this.router.navigate([`stories`]);

  }

标签: angularwordpressionic-frameworkionic-native

解决方案


当第 1 次完成时,您可以调用第 2 次请求。

例如:

firstRequest(){
    this.http.post("url", firstReqData, {
      headers: {
        "Authorization": "Basic xxxxxxx",
        "Accept": "application/json",
        "Content-Type": "application/json"
      }
    }).subscribe(data => {
      console.log(data);
      this.secondRequest(pass, your, data, to, second); // call this function to call your second request when first get completed
    }, error => {
      console.log(error);
    });
 }


secondRequest(get, your, data, to, second){ // get data to send it in 2nd request
    this.http.post("url", secondReqData, {
      headers: {
        "Authorization": "Basic xxxxxxx",
        "Accept": "application/json",
        "Content-Type": "application/json"
      }
    }).subscribe(data => {
      console.log(data);
    }, error => {
      console.log(error);
    });
 }

推荐阅读