【问题标题】:Wait for a subscribe method in Ionic等待 Ionic 中的订阅方法
【发布时间】:2019-05-10 01:27:25
【问题描述】:

我在提供者中有一个方法

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

我在另一个提供者中调用上述方法

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

这里我想停止代码的执行,直到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);

id 的输出是undefined。我认为这里有一个异步。

【问题讨论】:

  • 你能举一个必须等​​待的代码示例吗?
  • 我不确定你想要什么。你能提供更多细节吗?
  • 我不知道你为什么需要这个,但是 Angular 支持双向数据绑定,所以你不需要这样做。详细解释
  • 我已编辑问题,请查看。

标签: javascript angular typescript ionic2 ionic3


【解决方案1】:

将此代码放在类似的函数中

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

并在getProfile() 函数中调用此函数,如下所示

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

【讨论】:

    猜你喜欢
    • 2017-10-08
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2021-05-06
    • 2020-02-25
    • 1970-01-01
    相关资源
    最近更新 更多