【发布时间】:2020-08-19 15:41:02
【问题描述】:
请多多包涵,因为这个问题又长又详细,而且我对 RxJS 还很陌生。
我正在尝试在 Angular 中创建类似于 Windows Explorer 的 Amazon S3 浏览器。
左侧列表将包含所有根文件夹(它不会是树形视图),当单击任何根文件夹时,其中的子文件夹和文件将显示在右侧的详细信息视图中。
我需要为左侧列表中的每个根文件夹创建一个新的 S3 访问令牌。我有一个这样做的后端服务。此令牌在特定时间段内有效。所以当前token无效的情况有:-
- 如果用户单击左侧列表中的某个其他根文件夹。
- 如果令牌到期。
这是我为管理此令牌到期条件而编写的内容:-
private accessTokenSource: BehaviorSubject<AccessToken | null> = new BehaviorSubject(null);
accessToken$ = this.accessTokenSource.asObservable();
getAccessToken() {
return this.http.get(${this.accessTokenEndpoint}).pipe(
tap((accessToken) => {
// set Access token in a subject
this.accessTokenSource.next(accessToken);
}),
switchMapTo(timer(55*60*1000).pipe(
tap(() => {
// reset access token in subject since now token is invalid - Expiry case
this.accessTokenSource.next(null);
})
))
);
}
// Whoever subscribes to this will fetch the token and start the expiration timer
由于不想在视图层中公开访问令牌获取逻辑,我的每个左列表和详细信息组件都调用了 s3Service 中的方法 getDetails(currentPrefix: string)。该方法首先检查令牌的有效性是否能够调用 S3 API,然后调用listObjects 操作并返回结果。这是我到目前为止所拥有的:-
// Checks the validity of token for the current prefix
checkAccessTokenValidity(currentPrefix: string) {
let isTokenValid: boolean = true;
// This uses access token set in the subject
// According to me, it will be reset by the timer's tap operation (when it expires)
const sub = this.accessToken$.subscribe((token) => {
// Check token's expiry or usability for current folder and update isTokenValid accordingly
if(!token || !currentPrefix.includes(token.rootFolder)) {
isTokenValid = false;
}
});
sub.unsubscribe();
return isTokenValid;
}
// Public method to call from list and details components
getDetails(currentPrefix: string) {
const isTokenValid = this.checkAccessTokenValidity(currentPrefix);
if(!isTokenValid) {
// This will fetch the token and start the TIMER
this.getAccessToken().subscribe(() => {});
}
// I think that this will not work, since if getAccessToken takes time,
// then accessToken$ will still be invalid!
const objectList$ = this.accessToken$.pipe(
map(token => {
// S3 List Objects method here, with current token
})
)
}
如何解决检查令牌有效性然后等待我的服务返回新的有效令牌以调用 S3 API 的问题?任何帮助将非常感激。这种方法也可能是完全错误的,所以也请随时纠正我。
【问题讨论】:
标签: javascript angular amazon-s3 rxjs