繁体   English   中英

如何等待函数在角度2中完成执行?

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

下面是我的代码,我希望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来返回一个observable。 然后你的其他函数可以订阅该函数并在subscribe函数中执行它们的操作。 Angular 2 HTTP教程给出了一个例子

暂无
暂无

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

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