javascript - 如何等待函数在 Angular 2 中完成执行?

标签 javascript angularjs angular angular-promise

下面是我的代码,我希望 login()authenticated() 函数等待 getProfile() 函数完成执行.我尝试了几种方法,例如 promise 等,但我无法实现。请给我建议解决方案。

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig }        from './auth.config';

// Avoid name not found warnings
declare var Auth0Lock: any;

@Injectable()
export class Auth {
  // Configure Auth0
  lock = new Auth0Lock(myConfig.clientID, myConfig.domain, {
    additionalSignUpFields: [{
      name: "address",                              // required
      placeholder: "enter your address",            // required
      icon: "https://example.com/address_icon.png", // optional
      validator: function(value) {                  // optional
        // only accept addresses with more than 10 chars
        return value.length > 10;
      }
    }]
  });

  //Store profile object in auth class
  userProfile: any;

  constructor() {
    this.getProfile();  //I want here this function to finish its work
  }


  getProfile() {
    // Set userProfile attribute if already saved profile
    this.userProfile = JSON.parse(localStorage.getItem('profile'));

    // Add callback for lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);

      // Fetch profile information
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // Handle error
          alert(error);
          return;
        }

        profile.user_metadata = profile.user_metadata || {};
        localStorage.setItem('profile', JSON.stringify(profile));
        this.userProfile = profile;
      });
    });
  };

  public login() {
    this.lock.show();
    this.getProfile();  //I want here this function to finish its work
  };

  public authenticated() {
    this.getProfile();  //I want here this function to finish its work
    return tokenNotExpired();
  };

  public logout() {
    // Remove token and profile from localStorage
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.userProfile = undefined;
  };
}

最佳答案

就像您在评论中看到的那样,您必须使用 PromiseObservable 来实现这一点,因为您的行为非常简单,您应该使用 Promise 因为 Observable 会有很多你在这种情况下不需要的特性。

这是您服务的 Promise 版本:

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig }        from './auth.config';

// Avoid name not found warnings
declare var Auth0Lock: any;

@Injectable()
export class Auth {
  // Configure Auth0
  lock = new Auth0Lock(myConfig.clientID, myConfig.domain, {
    additionalSignUpFields: [{
      name: "address",                              // required
      placeholder: "enter your address",            // required
      icon: "https://example.com/address_icon.png", // optional
      validator: function(value) {                  // optional
        // only accept addresses with more than 10 chars
        return value.length > 10;
      }
    }]
  });

//Store profile object in auth class
userProfile: any;

constructor() {
    this.getProfile();  //I want here this function to finish its work
  }


getProfile():Promise<void> {
    return new Promise<void>(resolve => {
    // Set userProfile attribute if already saved profile
    this.userProfile = JSON.parse(localStorage.getItem('profile'));

    // Add callback for lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);

      // Fetch profile information
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // Handle error
          alert(error);
          return;
        }

        profile.user_metadata = profile.user_metadata || {};
        localStorage.setItem('profile', JSON.stringify(profile));
        this.userProfile = profile;
        resolve()
      });
    });
   })
};

public login(): Promise<void>{
    this.lock.show();
    return this.getProfile();  //I want here this function to finish its work
  };

  public authenticated():void{
    this.getProfile().then( () => {  
        return tokenNotExpired();
    });
  };

  public logout():void {
    // Remove token and profile from localStorage
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.userProfile = undefined;
  };
}

关于 Promise 的更多信息 here

关于javascript - 如何等待函数在 Angular 2 中完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645491/

相关文章:

forms - 选择地址时, Angular 形式不验证

javascript - 错误 - 在主页上添加文本计数器后(使用 Jquery 计算剩余字符) - 需要刷新页面

javascript - 使用 Protractor 调试时,元素找不到 DOM 节点时,如何获取使用的原始选择器?

javascript - 将整个对象以 Angular 2 从一个组件发送到另一个组件

javascript - 在 Angular 中使用持久性 CSRF-TOKEN cookie 的风险

javascript - Angular $routeParams 空对象

Angular 在尝试导航应用程序时抛出错误

javascript - Angular 2 Rxjs 在服务器响应后创建 Action

javascript - 将 Javascript 正则表达式转换为 PHP 正则表达式?

javascript - 在 Angular JS 中,模型值的变化没有反射(reflect)在指令的模板中