2017-10-04 26 views
0

我有一个使用ngrx/store来维护应用程序状态的Angular应用程序。使用observable作为有效负载的调度行为

在我的根组件中,我想调度一个动作来设置状态中侧边栏的可见性。此刻,我的代码看起来是这样的:

export class AppComponent implements OnInit { 

    title = 'ye'; 
    isSidenavVisible$: Observable<boolean>; 
    private isSidenavVisible: boolean; // Is this really needed? 

    constructor(private store: Store<State>) { 
    this.isSidenavVisible$ = this.store.select(getIsSidenavVisible); 
    } 

    ngOnInit() { 
    this.isSidenavVisible$.subscribe(isSidenavVisible => { 
     this.isSidenavVisible = isSidenavVisible; 
    }); 
    } 

    toggleSidenav() { 
    this.store.dispatch(new SetSidenavVisibility(!this.isSidenavVisible)); 
    // I would like to dispatch the observable as a payload instead 
    } 
} 

即使这个工作,我想摆脱的(在我看来)多余private isSidenavVisible可变的,能够与唯一的工作结束了可观察到的isSidenavVisible$

减速机中的初始状态设置为true

这是否可能,如果是这样,我可以通过什么方式进一步简化我的代码?

+0

如果而不是使用可观察到,如果你使用BehaviourSubject作为isSidenavVisible $的类型,那么你可以这样做isSidenavVisible $ .getValue() HTTPS:/ /github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md –

+0

'BehaviourSubject'看起来很有趣,感谢您的链接! –

+0

让我知道它是否适用于ngrx商店。 –

回答

0

而不是采用替代方法BehaviourSubject方法,我选择临时订阅toggleSidenav()函数中的可观察值。

toggleSidenav() { 
    this.isSidenavHidden$.first().subscribe(isVisible => { 
    this.store.dispatch(new SetSidenavVisibility(!isVisible)); 
    }); 
} 

结果是根据需要,无需使用专用值变量,因为我用.first()订阅将自动取消订阅。

0

你不能只通过async pipe直接绑定observable到侧栏可见性并直接在模板中解析它?

0

绑定观察到在到侧边栏模板,async

export class AppComponent implements OnInit { 

    title = 'ye'; 
    isSidenavVisible$: Observable<boolean>; 

    constructor(private store: Store<State>) { 
    this.isSidenavVisible$ = this.store.select(getIsSidenavVisible); 
    } 

    ngOnInit() { 
    /* This is not needed because the default value is set in the reducer 
    this.isSidenavVisible$.subscribe(isSidenavVisible => { 
     this.isSidenavVisible = isSidenavVisible; 
    }); */ 
    } 

    toggleSidenav() { 
    this.store.dispatch({type: 'TOGGLE_NAVBAR'}); //The logic used to toggle the sidenav is in the reducer 
    } 
} 

且模板中像这样

<div *ngIf="isSidenavVisible$ | async">my content to hide</div> 

必须使用reducers

中的toogle代码可以是什么像这样:

export const toggleReducer = (state = false, {type, payload}) => { //state = false is the initial condition 
    switch(type){ 
    case TOGGLE_NAVBAR: 
     return !state; 
    default: 
     return state; 
    } 
} 

here是plunker,如果你想看到一个工作示例