如果订阅者未在 2/4/6 角完成,如何等待返回语句 [英] How to wait return statement if subscriber not completed in angular 2/4/6

查看:20
本文介绍了如果订阅者未在 2/4/6 角完成,如何等待返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在处理 Angular6 项目,并且我有 auth-http-interceptor.此文件中的问题是我想每次都从 angular4-adal 服务获取刷新令牌/获取令牌,为此,我必须订阅获取令牌,该令牌将提供令牌,然后想在 authReq 对象中分配该令牌.

Currently I am working on the Angular6 project, and I have auth-http-interceptor. The problem in this file is that I want to get refresh token/acquire token from angular4-adal service every time, and for that, I have to subscribe the acquire token which will give the token and then want to assign that token in authReq object.

但是我的拦截方法的返回类型是 Observable.

But my intercept method's return type is Observable.

那我怎么能等到订阅获取令牌然后返回next.handle(authReq).我尝试编写下面的代码,但它抛出一个错误 => 声明类型既不是void"也不是any"的函数必须返回一个值.

Then how could I wait for subscribing the acquire token and then return next.handle(authReq). I have tried to write the below code, but its throwing an error => A function whose declared type is neither 'void' nor 'any' must return a value.

auth-http-interceptor.ts

auth-http-interceptor.ts

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
    constructor(private adalService: AdalService, private loaderService: LoaderService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.adalService.acquireToken('###myTenantId').subscribe((token) => {
            this.loaderService.display(true);
            const authReq = req.clone({
                url: environment.apiUrl + req.url,
                headers: req.headers
                .set('Content-Type', 'application/json')
                .set('Authorization', 'Bearer ' + token)
            });
        return next.handle(authReq).finally(() => this.loaderService.display(false));
        });
    }
}

感谢任何帮助.

推荐答案

您缺少 return 并且无法从 subscribe 返回任何内容.您可以使用 flatMap 首先获取令牌,然后返回请求,还可以重新放置 finally 并且您还应该有某种错误处理程序:

You are missing a return and also you cannot return anything from subscribe. You could use flatMap to first fetch the token, and then return the request, also re-place your finally and you should have some kind of error handler as well:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.adalService.acquireToken('###myTenantId').flatMap((token) => {
        this.loaderService.display(true);
        const authReq = req.clone({
            url: environment.apiUrl + req.url,
            headers: req.headers
            .set('Content-Type', 'application/json')
            .set('Authorization', 'Bearer ' + token)
        });
      return next.handle(authReq);
    })
    .catch((err) => {
      // error handling here
      return Observable.throw(err)
    })
    .finally(() => this.loaderService.display(false));
}

这篇关于如果订阅者未在 2/4/6 角完成,如何等待返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆