简体   繁体   中英

how execute 'http get' synchronous inside a promise ? Angular 2 +Ionic 3

I am not sure if the title question is correct so i would like to achieve this :

I am trying to save JSON data in storage of ionic, my function return a promise so i would like to execute http.get inside this function to get data and save in storage .

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;
  }

I am using json for now because url will be change for URi, json is :

[
    {
      "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"
        }
      ]
    }
  ]

When i check it , the result is :

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

it doesnt add another profiles.

I am doing that to change of menu and profile picture depending if user choose another profile when click in menu change button and it`ll show modal with profiles that have active=0 , if you know another way to do creating a global variable in angular please tell me .

To make the request working, put your request in a service and call it.

If you don't know how to create a service and how it is supposed to work, check the service part of this tutorial . But now here is how to do it.

Put your request in a service:

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));
  }
}

Put your service in the 'providers' section of your module for example in app.module.ts :

providers: [ MyService ]

And then call myRequest from your service in your component:

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

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

It will work even if you're returning a Promise or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM