简体   繁体   English

等待Ionic中的订阅方法

[英]Wait for a subscribe method in Ionic

I have a method in a provider 我在提供程序中有一种方法

getProfile() {
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    return this.http.get(this.db_url + 'profile',{headers: headers})
      .map(res => res.json());
  }

I'm calling the above method in another provider as 我在另一个提供商中调用上述方法

getProfile() {
    this.authService.getProfile().subscribe((profile: any) => {
      this.profile = profile.user._id;
    },(err : any) => console.log(err))
  } 

Here I want to stop the execution of the code until this.profile = profile.user._id this line is executed.In the same provider where I declare the getProfile() method, I have the http request as 在这里我要停止执行代码,直到执行this.profile = profile.user._id这行。在声明getProfile()方法的同一provider中,我将http请求作为

let headers = new Headers();
    headers.append('Content-Type','application/json');
    let selected = {
      address: home.address, 
      date: new Date(),
      id: this.profile // from the getProfile() file.
    }

console.log(selected);

The output for the id is undefined . id的输出是undefined I think there is an async here. 我认为这里存在异步。

put this code in a function like 将此代码放在类似的函数中

setHeadres(){
 let headers = new Headers();
 headers.append('Content-Type','application/json');
 let selected = {
  address: home.address, 
  date: new Date(),
  id: this.profile // from the getProfile() file.
 }
}

and call this function inside getProfile() function like below 并在getProfile()函数内调用此函数,如下所示

getProfile() {
 this.authService.getProfile().subscribe((profile: any) => {
   this.profile = profile.user._id;
   this.setHeaders();
 },(err : any) => console.log(err))
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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