如何等待函数在角度2中完成执行? [英] How to wait for a function to finish its execution in angular 2.?
问题描述
下面是我的代码,我想要 login()
和 authenticated()
等待<$ c的函数$ c> getProfile()函数完成执行。我尝试了几种方式,比如承诺等,但我无法实现它。请建议我解决方案。
Below is my code, I want login()
and authenticated()
functions to wait for getProfile()
function to finish its execution. I tried several ways like promise etc. but I couldn't implement it. Please suggest me the solution.
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;
};
}
推荐答案
就像你在评论中看到的那样,你必须使用 Promise
或 Observable
来实现这一点,因为你的行为非常简单,你应该使用承诺
因为 Observable
会有很多你在这种情况下不需要的功能。
Like you saw in the comments, you have to use Promise
or Observable
to achieve this, since your behaviour is pretty simple, you should use Promise
because Observable
will have a lot of features you don't need in this case.
以下是您的服务的承诺
版本:
Here is the Promise
version of your service:
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;
};
}
更多关于承诺
此处
这篇关于如何等待函数在角度2中完成执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!