How to wait return statement if subscriber not com

2019-07-25 03:42发布

问题:

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.

But my intercept method's return type is Observable.

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

@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));
        });
    }
}

Any help is appreciated.

回答1:

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));
}