javascript - 等待 Ionic 中的订阅方法

标签 javascript angular typescript ionic2 ionic3

我在提供者中有一个方法

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 这行代码。在我声明的同一个 providergetProfile() 方法,我的 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(选定);

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

最佳答案

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

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

关于javascript - 等待 Ionic 中的订阅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683772/

相关文章:

javascript - jQuery 如何劫持 "this"?

angular - 如何在 switchMap 中使用过滤器?

javascript - Angular Http 发布到 .Net Core

css - Angular8:为什么我在这些 Angular Material 卡之间没有空间?

javascript - 为什么 Swiper 在 Angular 上不适合我?

php - 时间同步与高延迟

javascript - Vuejs - 无法读取未定义的属性 '_withTask'

javascript - 如何在 React 中有条件地渲染图像?

Angular LoadChildren 字符串格式已弃用,但函数格式会导致错误

angular - 如何在 Angular 2 中迭代 JSON 对象?