Angular,ngrx / store,在单个序列中存储select和async调用

时间:2017-06-08 15:25:19

标签: angular typescript rxjs ngrx ngrx-store

有人知道是否有机会从商店获取价值然后调用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,但如果多次调用拦截器,它将无效。

2 个答案:

答案 0 :(得分: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以这种方式在全局Reducer文件中创建reselect方法:

export const getAccessToken = createSelector(
  getAuthState, authReducer.getToken);

答案 1 :(得分:2)

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

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

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