javascript - 如何在 Promise 中同步执行 'http get' ? Angular 2 + ionic 3

标签 javascript angular ionic-framework ionic3

我不确定标题问题是否正确,所以我想实现这一目标:

我正在尝试将 JSON 数据保存在 ionic 存储中,我的函数返回一个 promise ,因此我想在该函数内执行 http.get 来获取数据并保存在存储中。

saveStorage() {
    let promesa = new Promise((resolve, reject) => {
      //Check if user is in Mobile or Web
      if (this.platform.is("cordoba")) {
        this.storage.set('userJson', this.userObject);

        //dispositivo
        this.storage.set('password', this.user.password);
        this.storage.set('name',this.user.email);
      } else {
        //Desktop
        if (this.user.password) {
          //Save User
          localStorage.setItem("userJson", JSON.stringify(this.userObject));
          localStorage.setItem("password", this.user.password);
          localStorage.setItem("name", this.user.email);

          //save profiles to show menu depending profile
          let profiles=[];

          profiles.push({
            "name":"Admin",
            "profile":"user",
            "isActive":1,
            "page":"",
            "menu":""
          });
          /*THIS PART DOESNT WORK*/

          //Get another profiles from service

          let url='assets/data/userProfiles.json';

          let jsonArr=[];
          this.http.get(url).subscribe(data => {
            console.log(data);
            data[0].companies.forEach(function(cur){
              jsonArr.push({
                name: cur.name,
                profile: "company",
                isActive:0,
                page:"",
                menu:""
              });
            })
            data[1].centers.forEach(function(cur){
              jsonArr.push({
                name: cur.name,
                profile: "center",
                isActive:0,
                page:"",
                menu:""

              });
            })
            profiles.push(jsonArr);


          }, err => {
            console.log(err);
          });
          localStorage.setItem("profiles", JSON.stringify(profiles));
        } else {
          localStorage.removeItem("userJson");
          localStorage.removeItem("profiles");
          localStorage.removeItem("password");
          localStorage.removeItem("name");
        }
      }
    })
    return promesa;
  }

我现在使用 json,因为 url 将针对 URi 进行更改,json 是:

[
    {
      "companies": [{
        "id": 1,
        "name": "Prueba",
        "company_number": "23423423A",
        "latitude": 241241.12,
        "longitude": 213213.12,
        "country": "ES"
      },
        {
          "id": 2,
          "name": "Prueba2",
          "company_number": "23423423A",
          "latitude": 241241.12,
          "longitude": 213213.12,
          "country": "US"
        },
        {
          "id": 3,
          "name": "Prueba3",
          "company_number": "23423423AB",
          "latitude": 241241.19,
          "longitude": 213213.20,
          "country": "US"
        }
      ]
    },
    {
      "centers":[
        {
          "id": 1,
          "name": "Prueba",
          "center_number": "23423423A",
          "latitude": 241241.12,
          "longitude": 213213.12,
          "country": "ES"
        },
        {
          "id": 2,
          "name": "Prueba2",
          "center_number": "23423423A",
          "latitude": 241241.12,
          "longitude": 213213.12,
          "country": "US"
        }
      ]
    }
  ]

当我检查它时,结果是:

[{"name":"Admin","profile":"user","isActive":1,"page":"","menu":""}]

它不会添加其他配置文件。

我这样做是为了更改菜单和个人资料图片,具体取决于用户在单击菜单更改按钮时是否选择另一个配置文件,并且如果您知道创建全局的另一种方法,它将显示具有 active=0 的配置文件的模式 Angular 变量请告诉我。

最佳答案

要使请求正常工作,请将您的请求放入服务中并调用它。

如果您不知道如何创建服务以及它应该如何工作,请检查 this tutorial 的服务部分。但现在这里是如何做到这一点。

将您的请求放入服务中:

import { Injectable }      from '@angular/core';
import { Http }            from '@angular/http';
import { Response }        from '@angular/http';
import { Observable }      from 'rxjs/Observable';   
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'; 

@Injectable()
export class MyService
{
  constructor(private http : Http){}

  public myRequest() {
    this.http.get(myUrl).map((res: Response) =>
    {
      return res.json();
    })
    .catch((error: any) => Observable.throw(error));
  }
}

将您的服务放在模块的“providers”部分,例如在 app.module.ts 中:

providers: [ MyService ]

然后从组件中的服务调用 myRequest:

...
constructor(private myService : MyService){}

this.myService.myRequest().subscribe(
  (res) =>
  {
    // do what you want
  },
  (err) =>
  {
    // error
  }
);

无论你是否返回 Promise,它都会起作用。

关于javascript - 如何在 Promise 中同步执行 'http get' ? Angular 2 + ionic 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654232/

相关文章:

javascript - 为什么我在实现自动完成功能时收到 "Object does not support autocomplete jquery method"运行时错误?

javascript - 如何在 Angular 2 中使用 Protractor ?

typescript - `enableProdMode()` 时到底发生了什么

angular - 发生未处理的异常 : The requested module 'sourcemap-codec' does not provide an export named 'decode'

android - 使用 google redirect_uri_mismatch 登录 ionic 框架

android - 在 Ionic 2 中进行 HTTP POST 调用会给出禁止响应

javascript - 注释嵌套参数

javascript - 减少整数有效,相同增加整数无效

javascript - 如何让 eval 使用本地范围

javascript - 如何只影响 for 循环列表中的一项?