创建了可以接受任何类型的泛型StateManagierService,在状态改变时,用户可以获得新的状态和数据(如果有的话).但是你看,我遗漏了一些东西.
export class StateManagierService<T> {
private _state$: BehaviorSubject<T>;
protected constructor (initialState: T) {
console.log("initialState",initialState)
this._state$ = new BehaviorSubject(initialState);
}
get state$ (): Observable<T> {
return this._state$.asObservable();
}
get state (): T {
return this._state$.getValue();
}
changeState (nextState: T): void {
if(this.state === nextState || nextState === null) return;
this._state$.next(nextState);
}
}
用户可以创建的不同州
export enum state1{
A =1,
B
}
Wraper类将创建Obj并可以添加更多数据|属性
export class Wrap {
constructor(stateId: state1, data?:any){
console.log("stateId", stateId, data)
}
}
@Injectable({
providedIn: 'root'
})
export class serviceImpl extends StateManagierService<Wrap> {
constructor(){
super(new Wrap(state1.A, 'text1')); // Expecting Wrap object to set but not
}
}
测试服务判断
class hello {
constructor(private serviceImpl: serviceImpl){
}
one(){
this.serviceImpl.state$.subscribe(res=>{
console.log('res', res) // Expecting Wrap object What im doing wrong
})
this.serviceImpl.changeState(new Wrap(state1.B, 'text23'))
}
}