如何将ang2 @ngrx / store传递给http拦截器以提醒401/3的app?

时间:2016-11-24 14:40:35

标签: angular ngrx

是否可以将redux存储传递给angular2中的拦截器?我需要在用户会话到期时触发应用程序更改,并通过redux存储找出最简单的方法。

这是我的拦截器类:

@Injectable()
export class CrowdHttp extends Http {
    constructor(
        backend: ConnectionBackend,
        defaultOptions: RequestOptions,
        private _router: Router,
        private store: Store<any>)
    {
        super(backend, defaultOptions);
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            console.log( this.store );
            if (err.status  == 401 ) {
                this.store.dispatch(new NewLoggedInUserAction(null));
                return Observable.empty();
            } else {
                console.log( err );
                this.store.dispatch(new NewLoggedInUserAction(null));
                return Observable.throw(err);
            }
        });
    }

但是所述类包含在主app.module.ts

的提供者中
@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        ReactiveFormsModule,
        AppRoutingModule,
        StoreModule.provideStore(
            StoreLoader.reducers(),
            StoreLoader.initialState()
        ),
        StoreDevtoolsModule.instrumentStore({
            monitor: useLogMonitor({
                visible: BootstrapDataService.reduxStoreDebug(),
                position: 'right'
            }),
        }),
        StoreLogMonitorModule
    ],
    declarations: [
        CrowdComponent,
    ],
    bootstrap: [CrowdComponent],
    providers: [
        AuthGuard,
        BootstrapDataService,
        AuthService,
        AuthResolver,
        {
            provide: APP_BASE_HREF,
            useValue: window.crowdRoute
        },
        {
            provide: Http,
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router) => new CrowdHttp(xhrBackend, requestOptions, router, store),
            deps: [XHRBackend, RequestOptions, Router]
        },
        {
            provide: BrowserXhr,
            useClass: CrowdBrowserXHR
        }
    ]
})
export class CrowdModule {
    constructor() {
        //optionally do something magical at this point...
    }
}

catch很好用,但我找不到将事件传递回应用程序其余部分的方法。传递的商店不包含调度函数并抛出错误:this.store.dispatch is not a function

我是以最好的方式接近这个还是有更好的选择?

1 个答案:

答案 0 :(得分:1)

尝试使用以下行替换httpapp.module.ts提供商的当前设置:

{
    provide: Http,
    useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, store: Store<any>) => new CrowdHttp(xhrBackend, requestOptions, router, store),
    deps: [XHRBackend, RequestOptions, Router, Store]
}