GVKun编程网logo

angular – ngrx – 对效果的奇怪行为(angular ng-model)

8

在本文中,我们将给您介绍关于angular–ngrx–对效果的奇怪行为的详细内容,并且为您解答angularng-model的相关问题,此外,我们还将为您提供关于Angular2Ngrx商店,效果和“

在本文中,我们将给您介绍关于angular – ngrx – 对效果的奇怪行为的详细内容,并且为您解答angular ng-model的相关问题,此外,我们还将为您提供关于Angular 2 Ngrx商店,效果和“短暂状态”、Angular 6 / NGRX组合减速器、Angular 9 + NGRX:在组件中捕捉效果完成的最佳方法、angular – ngrx /存储在动作/效果UI通知之后的知识。

本文目录一览:

angular – ngrx – 对效果的奇怪行为(angular ng-model)

angular – ngrx – 对效果的奇怪行为(angular ng-model)

正如标题中所述,我面临的问题是,只有在这些情况下,我的所有效果才能正常工作:

>我已经登录了
>我没有登录

如果我设法注销并与其他用户登录,则会出现问题.只有每个ngOnInitdoing动作调度都会被调用.没有效果被解雇.

我有两个模块,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());
}

test.actions.ts:

import { Action } from '@ngrx/store';

export const ActionTypes = {
    LOAD: type('[Test] Load'),LOAD_SUCCESS: type('[Test] Load Success'),};

export class LoadAction implements Action {
    type = ActionTypes.LOAD;
    constructor() {}
}

export class LoadActionSuccess implements Action {
    type = ActionTypes.LOAD_SUCCESS;
    constructor(public payload: SomeType) {}
}

export type Actions
  = LoadAction
  | LoadActionSuccess

test.effects.ts:

@Injectable()
export class TestEffects {
  @Effect() load$= this.actions$
    .ofType(testActions.ActionTypes.LOAD)
    .map(toPayload)
    .switchMap(() => this._testService.getStuff()
      .map(result => new testActions.LoadActionSuccess(result))
      .catch((error) => Observable.of({type: error}))
    )
  ;

  constructor(private _testService: TestService,private actions$: Actions) {}
}

test.reducer.ts:

import { createSelector } from 'reselect';
import { Action } from '@ngrx/store';
/** ngrx **/
import * as sidebaractions from '../actions/test.actions';

export interface State {
    stuff: SomeType
};

export const initialState: State = {
    stuff: new SomeType()
};

export function testReducer(state = initialState,action: Action): State {
    switch (action.type) {
        case testActions.ActionTypes.LOAD_SUCCESS:
            return {
                stuff: new SomeType(action.payload)
            }
        default: {
            return state;
        }
    }
}

export const getStuff = (state: State) => state.stuff;

在我的package.json中,我有:

{
    "dependencies" : {
        "@angular/core": "^4.0.0",. . .,"@ngrx/core": "^1.2.0","@ngrx/effects": "^2.0.4","@ngrx/store": "^2.2.3",. . .
    },"devDependencies" : {
        . . .
        "ngrx-store-freeze": "^0.1.9",. . .
    }
}

我真的不明白这种行为.我还对ngrx github问题和this one等相关问题进行了掠夺,但我真的无法解决这个问题.

I’m guessing it may be caused by the fact that I have these two
different modules

编辑:

在app.module中移动效果及其服务会导致相同的行为.

我究竟做错了什么?

解决方法

它出来的问题是由旧版本的ngrx引起的.我设法在 migration guide之后将所有内容升级到版本4.1.1以及README中的不同指令.

Angular 2 Ngrx商店,效果和“短暂状态”

Angular 2 Ngrx商店,效果和“短暂状态”

在表单组件的上下文中工作:

我试图向用户显示表单的状态“待定,成功,错误,原始”.我不想在商店中拥有这些状态,因为它们是“短暂的状态”.

我有一个影响:

@Effect()
  addTagToVideoEffect_ = this.appState_
    .ofType(TagActions.ADD_TAG_TO_VIDEO)
    .map<AddTagToVideo>(action => action.payload)
    .switchMap((addTag: AddTagToVideo) => this.dtsiVideosService.addTagToVideo(addTag)
      .map((addTag: AddTagToVideo) => TagReducers.addTagToVideoComplete(addTag))
      .catch((err) =>Observable.throw(err))
    );

在我的表单组件中,我将调度TagActions.ADD_TAG_TO_VIDEO并订阅它:

onTag(tag: TagEntity) {

    this.subscription = this.tagActions.addTagToVideoEffect_.subscribe(
      this.onAddTagSuccess,this.onAddTagError
    );

    this.tagActions.addTagToVideo({videoId: this.videoId,tag: tag});
}

.tagActions.addTagToVideoEffect_.subscribe导致我的效果被调用两次.如何在没有经过商店的所有短暂状态的情况下获得视图中效果的结果?并没有被称为两次的效果……

解决方法

你两次获得效果调用的原因是因为它只是一个Observable.您需要将其转换为发布者.

@Effect()
  addTagToVideoEffect_ = this.appState_
    .ofType(TagActions.ADD_TAG_TO_VIDEO)
    .map<AddTagToVideo>(action => action.payload)
    .switchMap((addTag: AddTagToVideo) => this.dtsiVideosService.addTagToVideo(addTag)
      .map((addTag: AddTagToVideo) => TagReducers.addTagToVideoComplete(addTag))
      .catch((err) => Observable.throw(err))))
    .share();

然后你可以在你的视图中使用它:

tagFormState_: BehaviorSubject<FormState> = new BehaviorSubject<FormState>({});


  onTag(tag: TagEntity) {

  Observable.from(this.tagActions2.addTagToVideoEffect_)
  .first()
  .toPromise()
  .then(this.onAddTagSuccess,this.onAddTagError)

    this.tagFormState_.next({pending: true});
    this.tagActions.addTagToVideo({videoId: this.videoId,tag: tag});
  }


  onAddTagSuccess = (payload) => {
    this.tagFormState_.next({success: 'Success !'});
    this.resetTagFormState();
  }

  onAddTagError = (err) => {
    this.tagFormState_.next({error: err.message});
    this.resetTagFormState();
  }

  resetTagFormState() {
    setTimeout(_=> {
      this.tagFormState_.next({});
    },1000);
  }

关于这个主题的资源帮助我解决了这个问题:

> https://github.com/ReactiveX/RxJS/issues/1135
> https://github.com/ReactiveX/rxjs/issues/1420
> https://egghead.io/courses/rxjs-subjects-and-multicasting-operators

Angular 6 / NGRX组合减速器

Angular 6 / NGRX组合减速器

我正在使用Angular 6 w / NgRX 4.我有多个我想要结合的减速器.

app.module.ts

import { browserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { StoreModule } from '@ngrx/store';
    import { EffectsModule } from '@ngrx/effects';

    import { StoreDevtoolsModule } from '@ngrx/store-devtools';

    import { AppComponent } from './app.component';
    import counterEffects from './store/counter/counter.effects';

    import reducers from './store/reducers';

    @NgModule({
      declarations: [AppComponent],imports: [
        browserModule,StoreModule.forRoot(reducers),EffectsModule.forRoot([counterEffects]),StoreDevtoolsModule.instrument({
          maxAge: 10,}),],providers: [],bootstrap: [AppComponent],})
    export class AppModule {}

reducers.ts

import { combineReducers } from '@ngrx/store';
import { reducer as counterReducer,key as counterKey } from './counter';
import { reducer as profileReducer,key as profileKey } from './profile';

const appReducer = combineReducers({
  [counterKey]: counterReducer,[profileKey]: profileReducer,});

export default (state,action) => {
  if (action.type === 'REDIRECT_TO_EXTERNAL') {
    state = undefined;
  }

  return appReducer(state,action);
};

我的减速机是标准的减速机,没什么特别的.

来自React / Redux背景,我会像这样设置多个reducers,但是在Angular中,当我尝试从商店中选择时,我得到了未定义.当我尝试使用开发工具查看商店时,我看不到我的减速器和状态都不是{}

如何在Angular 6 / NgRX 4中设置多个减速器?

解决方法

import { ActionReducerMap } from '@ngrx/store';
import { reducer as counterReducer,key as profileKey } from './profile';

export interface IAppState {
  [counterKey]: any;
  [profileKey]: any;
}

export const reducers: ActionReducerMap<IAppState> = {
  [counterKey]: counterReducer,};

Angular 9 + NGRX:在组件中捕捉效果完成的最佳方法

Angular 9 + NGRX:在组件中捕捉效果完成的最佳方法

我知道两种方式:

  1. 使用{ dispatch: false }创建另一个效果,这意味着该效果不会调度任何动作,但可以执行一些逻辑操作,例如打开Snackbar。 (ofType<UserServerCreated (UserActionTypes.UserServerCreated))并仅添加一个tap运算符函数,并与catchError中的操作相同。
  2. 您也可以订阅组件到动作的频道。因此,您可以像效果一样过滤此通道。并执行与以前相同的逻辑,或保存此逻辑并在组件中发送消息。 Get error response from ngrx@effects to component
,

尝试

stateSubscription: any;     
 this.stateSubscription = this.store.dispatch(new UserServerCreation({ user: _user }));

  this.stateSubscription = this.store.pipe(select(fromAppLanguage.selectPageState)).subscribe((data) => {
        if (data && data != undefined) {
          if (data['code'] == 200) {

           console.log('---success')
            this.userForm.reset();
          } else {
           console.log('---err')
            this.toastr.error(data['message']);
            this.stateSubscription.unsubscribe();

          }
        }
      });

angular – ngrx /存储在动作/效果UI通知之后

angular – ngrx /存储在动作/效果UI通知之后

我正在使用ngrx / store和ngrx / effects.

这是流程,

>用户单击登录按钮
>登录已分派的行动
> $effects执行http.post凭据登录
>调度LOGIN_SUCCESS或LOGIN_FAILURE动作

问题:我想在执行操作后执行一些UI任务,例如,下拉模式,或显示错误消息的弹出窗口.

我如何订阅我的组件中的响应?

多谢你们.

解决方法

您的州应该有一个标志,通知您的组件应该执行操作.

像这样的东西:

州:

const initialState: SomeState = {
    loggedIn: false,...
};

export default function(state = initialState,action: Action): SomeState {
    switch (action.type) {
        case StateActions.LOGIN_SUCCESS:
            return Object.assign({},state,{loggedIn: true});
            ...

然后在你的组件中订阅状态,如果loggedIn为true,你知道你应该例如显示模态.

另一种方法是通过服务在您的效果中执行任务.

今天关于angular – ngrx – 对效果的奇怪行为angular ng-model的介绍到此结束,谢谢您的阅读,有关Angular 2 Ngrx商店,效果和“短暂状态”、Angular 6 / NGRX组合减速器、Angular 9 + NGRX:在组件中捕捉效果完成的最佳方法、angular – ngrx /存储在动作/效果UI通知之后等更多相关知识的信息可以在本站进行查询。

本文标签: