簡體   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