How to wait return statement if subscriber not completed in angular 2/4/6

老子叫甜甜 提交于 2019-12-11 05:30:39

问题


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


来源:https://stackoverflow.com/questions/51551895/how-to-wait-return-statement-if-subscriber-not-completed-in-angular-2-4-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!