在Angular中,可以通过创建一个共享服务来重用reducer和selectors,而无需使用redux。下面是一个示例解决方法:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private state = {
counter: 0
};
getState() {
return this.state;
}
dispatch(action) {
this.state = this.reducer(this.state, action);
}
private reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, counter: state.counter + 1 };
case 'DECREMENT':
return { ...state, counter: state.counter - 1 };
default:
return state;
}
}
}
在上面的示例中,SharedService具有一个私有state属性,它包含一个计数器。它还具有一个getState方法,用于获取当前状态,以及一个dispatch方法,用于分派操作并更新状态。
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-counter',
template: `
Counter: {{ counter }}
`
})
export class CounterComponent {
counter: number;
constructor(private sharedService: SharedService) {
this.counter = sharedService.getState().counter;
}
increment() {
this.sharedService.dispatch({ type: 'INCREMENT' });
this.counter = this.sharedService.getState().counter;
}
decrement() {
this.sharedService.dispatch({ type: 'DECREMENT' });
this.counter = this.sharedService.getState().counter;
}
}
在上面的示例中,CounterComponent注入SharedService,并在构造函数中获取当前计数器的状态。它还包含increment和decrement方法,这些方法分派相应的操作并更新计数器。
通过上述方法,您可以在不同的根中重用reducer和selectors,而无需使用redux。每个组件都可以注入SharedService并使用它来获取状态和分派操作。