在Angular 7中,如果NGRX Store的状态未定义,可能有几种原因。以下是一些可能的解决方法和代码示例:
import { StoreModule } from '@ngrx/store';
import { reducer } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot({ app: reducer }) // 使用你的reducer替换'reducer'
],
...
})
export class AppModule { }
export function reducer(state = initialState, action: Action) {
switch (action.type) {
...
default:
return state;
}
}
import { select } from '@ngrx/store';
import { Observable } from 'rxjs';
@Component({
...
})
export class MyComponent {
myState$: Observable;
constructor(private store: Store) {
this.myState$ = this.store.pipe(select('myState'));
}
}
import { Subscription } from 'rxjs';
export class MyComponent implements OnInit, OnDestroy {
myState: any;
subscription: Subscription;
constructor(private store: Store) { }
ngOnInit() {
this.subscription = this.store.pipe(select('myState')).subscribe(state => {
this.myState = state;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
以上是一些常见的解决方法和代码示例,可以根据具体情况进行调整。