我是RxJs的新手,我有一个API用于地理编码,提供如下函数:
simpleGeocode(options)
* where options = { address: {addr: ... }, success: Function, failure: Function}. The success function returns the geocoded LatLon object.
Run Code Online (Sandbox Code Playgroud)
我在Angular应用程序中使用NGRX Effects,所以我希望它能作为Observable使用,所以我可以使用标准的效果设置,如:
@Effect()
public calculateLocation: Observable<void> = this.actions
.ofType(actions.CALCULATE_LOCATION)
.switchMap((action) => {
let location = action.payload;
let options = {
address: location.address
};
// ...
this.geocodeService.simpleGeocode(options)
.map(latLon => new actions.CalculateLocationSuccessAction(latLon);
.catch(error => new actions.CalculateLocationFailureAction(error);
},
Run Code Online (Sandbox Code Playgroud)
但我完全不知道如何将该库调用包装成一个Observable.我从http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindCallback上读到了一些关于bindCallback()的信息,但我并不完全理解它.我确实理解它需要一个回调方法作为函数的最后一个参数,因此它看起来不适用于我的情况,因为成功和失败函数都作为对象的一部分传递给函数.
我如何从这个API方法中创建一个Observable,将成功回调映射到Observable的下一个,以及Observable的错误失败?
正如标题中所述,我面临的问题是,只有在这些情况下,我的所有效果才能正常工作:
如果我设法注销并与其他用户登录,则会出现问题.只有每个ngOnInit
执行动作调度的人都会被调用.没有效果被解雇.
我有两个模块,app.module和pages.module.第一个只声明未登录用户的组件,例如login/register/reset.第二个仅声明登录用户的组件.
在app.module.ts中我导入了所有的reducers并将其设置为StoreModule.provideStore(reducer)
.在pages.module.ts,另一个模块中,我导入并激活了类似的效果EffectsModule.run(TestEffects)
.
使用以下代码仅ngOnInit
调用内部日志.效果中的日志永远不会被调用.
test.component.ts:
/** ngrx **/
import * as reducers from '../../reducers';
import * as testActions from './actions/test.actions';
. . .
constructor(private _store: Store<reducers.State>){
this._store.select(reducers.getStuff)
.subscribe(stuff => console.log(stuff));
}
ngOnInit() {
console.log('Dispatching Load Action');
this._store.dispatch(new testActions.LoadAction());
}
Run Code Online (Sandbox Code Playgroud)
test.actions.ts:
import { Action } from '@ngrx/store';
export const ActionTypes = {
LOAD: type('[Test] Load'),
LOAD_SUCCESS: type('[Test] Load Success'),
}; …
Run Code Online (Sandbox Code Playgroud) 我试图通过使用CanDeactivate
(如果表单是脏的而不保存)来限制用户导航离开当前页面.当我们点击任何链接时,Router_Navigation
事件被调用并且它正在更新存储中的路由器状态,如果我取消模态弹出的页面导航(从可以停用),Router_Cancel
正在调用事件,但当前路由器状态是没有得到更新(它仍然指向其他页面).
我在ngrx
文档中看到了这个:
ROUTER_CANCEL和ROUTER_ERROR包含导航前的存储状态.使用先前的状态来恢复商店的一致性.
有人可以帮助我如何从Router_cancel
行动中获得以前的状态.
谢谢
I have a simple feature module, which provides services and imports its own stats fragment as a feature:
@NgModule({
imports: [
CommonModule,
StoreModule.forFeature('alarms', alarmsReducer, { initialState: alarmsInitialState }),
EffectsModule.forFeature([AlarmsEffects])
],
declarations: [],
providers: [
AlarmsFacade,
AlarmsService
]
})
export class AlarmsModule {
}
Run Code Online (Sandbox Code Playgroud)
And I'm importing this module in two other modules, a page that needs to have access to the services, and AppModule
as I need to import it here in order to have the state initialized properly.
When …
亲爱的 Stackoverflow 社区。
我是 NgRx 的新手,并试图找出它是如何工作的。我创建了一个应用程序 - 基于 Angular 6、Firebase 和 NgRx 的简单商店列表。
我在名为的集合中添加了几个项目,Product
并尝试通过 ngrx 模式获取它们。似乎我做得很好 - 我已经获取了项目作为有效载荷,GET_PRODUCTS_SUCCESS
但我无法将它们放入视图中进行显示,产品未定义。我尝试通过两种方式进行:
this.store.select(getProducts).subscribe(products => {
console.log('products', products); // undefined
});
Run Code Online (Sandbox Code Playgroud)
和
this.products = this.store.select(getProducts); // Store
Run Code Online (Sandbox Code Playgroud)
在第二种方式中,我只是得到了一个完整的商店......下面的代码。
product.actions.ts
import { Action } from '@ngrx/store';
import { Product } from '../../models/product.model';
export const GET_PRODUCTS = 'Get_products';
export const GET_PRODUCTS_SUCCESS = 'Get_products_success';
export class GetProducts implements Action {
readonly type = GET_PRODUCTS;
constructor(public payload = '') {}
}
export class GetProductsSuccess implements …
Run Code Online (Sandbox Code Playgroud) 如何在效果中访问我的状态?我当前的效果实现(如下所示)是在SEARCH_REUQUEST
分派动作时触发的。但是,在调用我的搜索服务以启动 HTTP 请求之前,我想访问一个状态以获取一些搜索参数。
@Effect()
SearchRequest$ = this.actions$
.ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST)
.pipe(
switchMap((action: fromSearchActions.SearchRequest) => {
return this.searchService
.search(action.payload, action.enrichmentId)
.pipe(
map(response => {
console.group("SEARCH effects");
console.log(response);
console.groupEnd();
return new fromSearchActions.SearchRequestSuccess(response);
}),
catchError(error =>
of(new fromSearchActions.SearchRequestFail(error))
)
);
})
);
Run Code Online (Sandbox Code Playgroud)
显然,我可以在这里利用一个 RxJS 运算符,但我似乎无法理解如何修改现有的效果实现以合并它。
@Effect()
SearchRequest$ = this.actions$
.ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST)
.withLatestFrom(this.featureStore.select(fromFeature.getCurrentSearchPageOptions))
.pipe(
switchMap((// How should this change? //) => { //Error
return this.searchService
.search(action.payload, action.enrichmentId, pageOptions)
.pipe(
map(response => {
console.group("SEARCH effects");
console.log(response);
console.groupEnd();
return new fromSearchActions.SearchRequestSuccess(response);
}),
catchError(error =>
of(new fromSearchActions.SearchRequestFail(error))
) …
Run Code Online (Sandbox Code Playgroud) 在对话响应的条件下,我对注销确认有这种效果,但出现以下错误:
错误错误:效果“AuthEffects.logoutConfirmation$”调度了一个无效的动作:未定义
和
错误类型错误:操作必须是对象
效果如下:
@Effect()
logoutConfirmation$ = this.actions$
.ofType<Logout>(AuthActionTypes.Logout)
.pipe(
map(action => {
if (action.confirmationDialog) {
this.dialogService
.open(LogoutPromptComponent)
.afterClosed()
.pipe(
map(confirmed => {
if (confirmed) {
return new LogoutConfirmed();
} else {
return new LogoutCancelled();
}
})
);
} else {
return new LogoutConfirmed();
}
})
);
Run Code Online (Sandbox Code Playgroud)
它在激活确认对话框时起作用,我想这是对话框响应的地图有问题,一直试图理解它但找不到方法。任何人都有这方面的线索?
我需要构建一个 Effect 并且我需要一个来自商店的值,问题是选择器是一个带参数的选择器。
按照示例代码:
@Effect()
ExampleEffect$ = this.actions$.pipe(
ofType(
ActionTypes.SOMETHING
),
map((action: Somthing) => action.payload.myParameter),
// HERE I NEED THE PARAMETER TO PERFROM THE SELECTION
withLatestFrom(this.store.pipe(select(selectorWithParamter(myParameter))),
map((value) => /* do somthing with the array [myParameter, valueSelected from sotre]*/)
Run Code Online (Sandbox Code Playgroud) 我有一个相当简单的问题,但无法弄清楚我做错了什么 - 我在网上找到的解决方案似乎都不适合我:
在打开我的应用程序的某个部分时,会分派一个操作以从后端加载当前的 item-Id 列表。
检索到此列表后 - 我需要加载我刚刚获得 id 的所有项目。
( GET /api/items -> [1,2] -> GET /api/items/1, GET /api/items/2)
Run Code Online (Sandbox Code Playgroud)
我试图用这样的效果来解决这个问题:
我选择了 mergeMap,因为我想发出一系列动作,但不关心它们的顺序。
这样做
@Effect() loadList$: Observable<LoadAction[]> = this.actions$.pipe(
ofType<LoadListAction>(LOAD_LIST_ACTION),
mergeMap( _ =>
this.backendService.getItemIds().pipe(
filter( it => it.items.length > 0),
map(response => response.items.map(it => new LoadAction(it.id));
)
)
)
);
Run Code Online (Sandbox Code Playgroud)
给我这个错误:
"invalid action was dispatched" [{"type":"[ITEMS][INIT] load item", "payload":"1"}, {"type":"[ITEMS][INIT] load item", "payload":"2"}],
TypeError: Actions must have a type property
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为 observable 现在直接发出数组,所以我切换到了两次 mergeMap:
@Effect() loadList$: Observable<LoadAction[]> = this.actions$.pipe( …
Run Code Online (Sandbox Code Playgroud) 我想在 ngrx store inits ( @ngrx/store/init
)时分派一个动作。我为此创建了一个效果:
@Effect()
reloadConext$ = this.actions$.pipe(
ofType(INIT),
switchMap(() => {
console.log('INIT ACTION');
//dispatch my action here
return of([]);
}
Run Code Online (Sandbox Code Playgroud)
调度 store init 操作时不会触发效果。我在 app.module 中注册了 root 的效果模块:
EffectsModule.forRoot([AppEffects]),
Run Code Online (Sandbox Code Playgroud)
如果我删除ofType
操作过滤器,则会触发事件。有谁知道 init 操作的过滤器不起作用?
提前致谢。