2

有谁知道是否有机会从商店获取价值然后调用 Angular http 服务?请参见下面的示例。提前致谢。

我有一个异步方法的服务。在这种方法中,我调用了 angular http 服务,但在调用 angular http 服务之前,我想从存储中检索一些值(oauth 访问令牌)。问题是我将 oauth 令牌存储在商店中,并且必须将令牌添加到请求中。如果服务器响应 401 错误,我会刷新令牌并使用新令牌重复请求或请求。

@Injectable()
export class Interceptor {
   public get(request: Request): Observable<any> {
      return this.store.select((s) => s.session.accessToken)
         // tried .switchMap, it wasn't working for multiple requests
         // .flatMap also is not working
         // commented below is working but I don't think that it is right solution
         // return Observable.of(request)
         // .withLatestFrom(this.store.select((s) => {
         //    return s.session.accessToken
         // }))
         // .flatMap(([config, accessToken]) => { ... })
         .flatMap((accessToken) => {
            request.headers.set("Authorization", `Bearer ${accessToken}`);

            return this.http.request(request);
         })
         .map((response) => {
            return response.json();
         })
         .catch((response) => {
            return this.handleError(response, request);
         });
   }

   // handle errors
   private handleError(response: Response, request: Request): Observable<Response> {
       // handle outdated api tokens
       if (response.status === HttpStatusesEnum.Unauthorized) {
           const deferredRequest = new DeferredRequestModel({ request });

           // appends HTTP request configuration object with deferred response
           // attached to buffer
           this.buffer(deferredRequest );

           return deferredRequest.observable;
       }

       // handle server error
       if (response.status === HttpStatusesEnum.InternalServerError) {
           ...
       }

       ...

       return Observable.throw(response);
   }
}

export class DeferredRequestModel {
    public observable: AsyncSubject<Response>;
    public request: Request;

    constructor(obj?: Partial<DeferredRequestModel>) {
        this.observable = new AsyncSubject<Response>();
        this.request = obj && obj.request || null;
    }

    public reject(error?: any): void {
        this.end({ isValue: false, value: error });
    }

    public resolve(value?: any): void {
        this.end({ isValue: true, value });
    }

    private end(result: any): void {
        if (this.observable.isStopped) {
            console.warn("Deferred already resloved/rejected.");
            return;
        }

        if (result.isValue) {
            this.observable.next(result.value);
            this.observable.complete();
        } else {
            this.observable.error(result.error);
        }
    }
}

然后当我调用一些服务时,它会通过拦截器发送请求。

export class SomeEffect {
   constructor(private someService: SomeService) {}

   @Effect()
   public someMethod(): Observable<Action> {
      return this.actions$.ofType(SOME_ACTION_GET)
         .map((action: SomeActions.Get) => action.payload)
         .switchMap((someObj) => {
            // someMethod call interceptor inside someService, it won't call angular 
            // http service directly
            return this.someService.someMethod(someObj);
         })
         .map((someResult) => {
            return new SomeActions.GetSuccess(someResult);
         });
   }
}

我尝试在拦截器中使用 switchMap,但如果拦截器被多次调用,它将不起作用。

4

2 回答 2

3

我会做这样的事情:

return this.store.select(reducers.getAccessToken)
  .take(1)
  .switchMap(token => {
    const headers = new Headers();
    headers.append('Authorization', `Bearer ${token}`);

    return this.http.get('...', { headers });
  });

getAccessToken方法是使用reselect以下方式在全局 reducers 文件中创建的:

export const getAccessToken = createSelector(
  getAuthState, authReducer.getToken);
于 2017-06-09T08:33:52.133 回答
2

如果您只对商店中包含的最后一个值感兴趣,您可以尝试以下操作:

public someMethod() {
   return this.store.select(s => s.config)
      .switchMap(config => {
         return this.http.request(config);
      });
}

虽然我会说只有在奇怪的情况下我才会将 Store 实例注入到服务中。也许您可以发布有关用例的更多信息

于 2017-06-08T20:12:40.973 回答