Angular 10:ngOnInit两个承诺



我目前正在尝试在我的Angular应用程序中实现与Strava API的连接。

要快速恢复:

  1. 用户点击按钮连接Strava
  2. 它被重定向到Strava进行身份验证(使用PKCE(
  3. Strava用代码重定向到我的应用程序
  4. 在ngonit中,我正在检查路由参数,如果我有代码,我会启动两个链接的承诺:第一个是从Strava获得访问令牌,然后是记录到DB(Firebase(中

问题是,有时数据记录在firebase中,有时却没有。这种行为不系统。奇怪的是,我每次都会进入我的postNewToken,因为控制台会记录它。

  • 如果我只是在ngOnInit((中记录到firebase(没有strava令牌请求(,它在100%的情况下都是创建的
  • 如果我有一个按钮,启动令牌请求并记录到firebase中,它似乎每次都能工作

我不知道如何解决它。这似乎更像是一个将promise链接到ngOnInit的问题,但我甚至不知道如何绕过它。

来自我的组件的代码:

ngOnInit() {
const stravaCode = this.route.snapshot.queryParamMap.get('code');
if (stravaCode !== undefined) {
this.stravaService.handleStravaAuthorizationCode(stravaCode);
}

在相关服务中:

// Handle Strava Code received
handleStravaAuthorizationCode(authorizationCode: string) {
this.getStravaToken(authorizationCode).then(res => {
this.postNewToken(res).then(res => {
this.router.navigate(['encoding']);
});
});
}
// Get Strava access token to make the requests to the API -> only done once
getStravaToken(authorizationCode: string){
if (authorizationCode !== undefined){
console.log('Authorization code: ' + authorizationCode);
const data = {
client_id: environment.strava.client_id,
client_secret: environment.strava.client_secret,
code: authorizationCode,
grant_type: 'authorization_code'
};
return this.http.post<StravaToken>(this.stravaTokenURL, data)
.pipe(catchError(this.errorService.handleHttpError)).toPromise();
}
}
postNewToken(stravaToken: StravaToken) {
if (this.authService.isLoggedIn) {
console.log('Recording strava token into Firebase');
console.log(stravaToken);
return this.afs.collection('strava_tokens')
.add(stravaToken).then(res => console.log(res), err => console.log(err));
} else {
return Promise.reject(new Error('No User Logged In!'));
}
}

终于明白了。我根本没有在等待建立与firebase的连接。因此,我无法发布任何新数据,因为我没有经过身份验证。

最新更新