gpt4 book ai didi

javascript - 使用 Promise 异步调用 Angular 2 中的两个函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:10 24 4
gpt4 key购买 nike

我在 auth.nav.service.ts 中有以下方法:

 public login () {
this.authService.login();
this.navService.redirectAfterLogin();
}

在 nav.service.ts 中:

public redirectAfterLogin () {
let nav = this.app.getRootNav();
nav.setRoot(TabsPage);
nav.popToRoot();
}

在 Auth.service.ts 中:

public login() {
const client = new Auth0Cordova(auth0Config);

const options = {
scope: 'openid profile offline_access'
};

client.authorize(options, (err, authResult) => {
if(err) {
throw err;
}

this.setIdToken(authResult.idToken);
this.setAccessToken(authResult.accessToken);

const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
this.setStorageVariable('expires_at', expiresAt);

this.auth0.client.userInfo(this.accessToken, (err, profile) => {
if(err) {
throw err;
}

profile.user_metadata = profile.user_metadata || {};
this.setStorageVariable('profile', profile);
this.zone.run(() => {
this.user = profile;

});

});

});
}

我想让登录功能成功运行并使用 RedirectAfterLogin。我怎样才能用 Promise 做到这一点?我正在使用 Angular 2、Ionic-Native 3 和 auth0。

最佳答案

我让它与一个 promise 一起工作,并修复了 then 范围内的变量(this)的范围。

auth.view.service.ts

 public login () {
var t = this; // this scope is lost inside the then.
this.authService.login().then(function (response){
t.navService.redirectAfterLogin();
});
}

auth.service.ts

 public login () {
return new Promise<any>((resolve, reject) => {

const client = new Auth0Cordova(auth0Config);

const options = {
scope: 'openid profile offline_access'
};

client.authorize(options, (err, authResult) => {
if(err) {
throw err;
}
this.setIdToken(authResult.idToken);
this.setAccessToken(authResult.accessToken);

const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
this.setStorageVariable('expires_at', expiresAt);

this.auth0.client.userInfo(this.accessToken, (err, profile) => {
if(err) {
throw err;
}

profile.user_metadata = profile.user_metadata || {};
this.setStorageVariable('profile', profile);
this.zone.run(() => {
this.user = profile;
resolve(profile);
}); // end zone run

}); // end userInfo

}); // end authorize
}); // end Promise
} // end login

(如果有更好的做法,请在评论中告诉我)请参阅:

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

javascript, promises, how to access variable this inside a then scope

关于javascript - 使用 Promise 异步调用 Angular 2 中的两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45121186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com