在angular 2中如何等待一个函数完成它的执行

How to wait for a function to finish its execution in angular 2.?

本文关键字:函数 一个 执行 何等待 angular 等待      更新时间:2023-09-26

下面是我的代码,我想让login()authenticated()函数等待getProfile()函数完成其执行。我尝试了一些方法,如承诺等,但我无法实现它。请给我一个解决方案。

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的信息在这里

我建议你设置getProfile来返回一个可观察对象。然后您的其他函数可以订阅该函数并在订阅函数中执行它们的操作。Angular 2的HTTP教程给出了一个这样的例子