这可能是因为组件在初始化时并没有正确订阅状态变化。可以使用ngOnInit生命周期钩子进行状态订阅并在组件初始化时更改图标颜色。
示例代码:
在组件.ts文件中:
import {Component, OnInit} from '@angular/core'; import {Store} from '@ngrx/store'; import {Observable} from 'rxjs/Observable'; import {AppState} from '../store/app.state';
@Component({
selector: 'app-icon-component',
templateUrl: './icon.component.html',
styleUrls: ['./icon.component.scss']
})
export class IconComponent implements OnInit {
iconColor$: Observable
constructor(private store: Store) {
}
ngOnInit() {
// 订阅状态变化
this.iconColor$ = this.store.select(state => state.iconState.color);
}
}
在组件.html文件中:
在ngrx样板中,记得定义一个 iconState 组件,同时,每次调用 reducer 都应该返回一个新的状态。
export interface IconState { color: string; }
export const initialIconState: IconState = { color: 'red' };
export function iconReducer(state: IconState = initialIconState, action: Action) { switch(action.type) { case 'CHANGE_COLOR': return { color: action.payload }; default: return state; } }