Developing a Data Generic State Management System in Angular using TypeScript

Implementing a Generic StateManagierService that can handle any type, allowing users to receive new state and data upon state change. However, something seems to be missing.

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);
  }
}

There are various States that users can define

export enum state1{
    A =1,
    B
}

The Wraper Class will create objects and allow for additional data or properties to be added

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 a Wrap object to be set but it is not happening
    }

}

A Test Service to verify functionality

class hello {
    constructor(private serviceImpl: serviceImpl){

    }
    one(){
        this.serviceImpl.state$.subscribe(res=>{
          console.log('res', res) // Expecting a Wrap object, what could I be doing wrong?
        })
        this.serviceImpl.changeState(new Wrap(state1.B, 'text23'))
    }
}

Answer №1

In order for Angular to quickly initialize properties in the constructor using the shorthand method, make sure it is defined as private stateId: state1. This simple step will resolve your problem!

Therefore,

<<Access Specifier>> <<propertyName>> : <<Property Type>>
, this is the correct format!

export class Wrap {
  constructor(private stateId: state1, private data?: any) { // <- modification made here!
    console.log('stateId', stateId, data);
  }
}

Check out the stackblitz demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

Vue3 project encountering issues with Typescript integration

When I created a new application using Vue CLI (Vue3, Babel, Typescript), I encountered an issue where the 'config' object on the main app object returned from the createApp function was not accessible. In VS Code, I could see the Typescript &ap ...

Tips for optimizing vendor.js and main.js files in Angular 15 using NX workspace

https://i.sstatic.net/8F9pX.pnghttps://i.sstatic.net/fD9TB.png Looking to enhance the performance of my login page and overall application by reducing the size of vendro.js and main.js files. Tried setting optimization : true in project.json for my NX wo ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

How can I obtain my .apk file?

I want to convert my app into .apk format. I inserted the following scripts on my "package.json" page: "build:development:android": "ionic cordova build android" and "build:production:android": "ionic cordova build android --prod --release". However, I ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

Utilizing Business Logic in a MEAN Stack Environment

When developing an Angular application, where should the calculations take place - on the front end or back end? Considering that the outputs need to update with each input change, is it practical to send a request to the back end every time there is an ...

Angular2 Navigation: Redirecting to a dynamically constructed route

To start, I need to automatically redirect to today's date as the default. Below is the routing configuration I currently have set up: import { CALENDAR_ROUTE } from './_methods/utils'; export const appRoutes: Routes = [ { path: Cal ...

Separate the generic function interface into its own type/interface variable

Below is an example of TypeScript generics that I found on typescriptlang. function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) { return obj[key]; } let x = { a: 1, b: 2, c: 3, d: 4 }; getProperty(x, "a"); getProperty ...

Encountering a type-safety problem while attempting to add data to a table with Drizzle

My database schema is structured like so: export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("c ...

Unable to show the data returned from service in Angular 2 component

I am facing an issue with my Angular 2 component that calls a service to retrieve data, but the data is not displaying on the HTML page. It seems that the roots array is coming back as a nested array. I have double-checked both the data and the HTML struct ...

What is the best way to clear the parent component's content from the child component in Angular?

Having an issue with Angular routes. The URLs are functioning properly, but when I navigate to the child component, specifically CreateEventComponent, the parent component's content from EventsComponent is also displayed. How can I make sure that th ...

What benefits does WebSocketSubject offer?

New to the world of web development, so please be patient with me... Current tech stack: Angular frontend, Tornado (Python-based) web server for the backend I've been successfully utilizing RxJs and WebSocket to communicate with the backend, followi ...

Dealing with nullable properties in Typescript

In my React Component code snippet, I am facing an issue with an optional field that needs to be initialized as undefined. This is causing difficulties when trying to use it after type checking. The problem arises in the context of using typescript version ...

An error was encountered when attempting to define a file that contains both a class and an interface with an expected sem

Seeking guidance on creating a Typescript file with a class and interface: export class Merchant { constructor( public id: string, public name: string, public state_raw: string, public users: string, ) {} }; export interface MerchantL ...

Retrieve unique elements from an array obtained from a web API using angular brackets

I've developed a web application using .NET Core 3.1 that interacts with a JSON API, returning data in the format shown below: [ { "partner": "Santander", "tradeDate": "2020-05-23T10:03:12", "isin": "DOL110", "type ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

Is tsconfig.json necessary for JS libraries without TypeScript to include a .d.ts file when shipping?

I am currently in the process of creating a .d.ts file for an established JavaScript library that does not utilize the TypeScript compiler or include any TypeScript code. Should I include a tsconfig.json file in the library to ensure proper interpretation ...

Using Angular to Bind Checkbox Value in Typescript

I have a challenge of creating a quiz where a card is displayed with 4 questions structured like this: <div class="col-md-6"> <div class="option" id="Answer1"> <label class="Answer1"> <input value= "Answer1" type="checkbox ...