Has create Generic StateManagierService which can accept any type, on Change of state the use can get new state and data if any. But look I m missing some thing.
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);
}
}
Different States which user can create
export enum state1{
A =1,
B
}
Wraper Class will create obj and can add more data| properties
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
}
}
Test Service to check
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'))
}
}
In-order for angular to initialize the properties in the constructor through the shortcut method, we need to define it like private stateId: state1
doing this solves your issue!
So <<Access Specifier>> <<propertyName>> : <<Property Type>>
this will be the format!
export class Wrap {
constructor(private stateId: state1, private data?: any) { // <- changed here!
console.log('stateId', stateId, data);
}
}