Home > Net >  Removing null or undefined from Angular observable
Removing null or undefined from Angular observable

Time:10-06

I am doing Angular state management using BehaviourSubject, but while pushing the data to store is adding undefined value to the end of the object (creating another undefined value). can any one suggest the way to remove?

{todos:[{"accountNo":"91957869","vpainfo":[{"vpa":"saasasa@fff"}]},undefined]}

The below are the sample snippets,

behaviourStore.ts

import {Observable, BehaviorSubject} from 'rxjs';

export class Store<T> {
    state$: Observable<T>;
    private _state$: BehaviorSubject<T>;

    protected constructor (initialState: T) {
        this._state$ = new BehaviorSubject(initialState);
        this.state$ = this._state$.asObservable();
    }

    get state (): T {
        return this._state$.getValue();
    }

    setState (nextState: T): void {
        this._state$.next(nextState);
    }
}

behaviourState.ts

export interface User {
    accountNo?: string;
    vpainfo: VPAinfo[]
  }
  export interface VPAinfo {
    vpa?: string;
  }
  export class BehaviourState {
    todos: User[]
  }

behaviourReducer.ts

import { Injectable } from '@angular/core';
import { Store } from './behaviourStore';
import { BehaviourState } from './behaviourState';
import * as fromActions from '../actions/users.actions';

@Injectable()
export class BehaviourReducer extends Store<BehaviourState> {
    constructor() {
        super(new BehaviourState());
    }
    callReducer(action: any) {
        switch (action.type) {
            case fromActions.ADD_TODO:
                this.setState({ ...this.state, todos: [action.payload.todo, ...this.state.todos] });
                break;
        }
    }
}

And finally adding the data in the below way,

const resultobj = {"accountNo":"91957869","vpainfo":[{"vpa":"saasasa@fff"]};
const action = { type: fromActions.ADD_TODO, payload: { todo: resultobj}};
this.behaviourReducer.callReducer(action);

CodePudding user response:

Since you have not defined any default value for todos. It's showing undefined.

Try this:

export class BehaviourState {
    todos: User[] = [];
 }

CodePudding user response:

That happens because the initial value of the todos is undefined, so you need either assign an initial value to it within the BehaviourState class, like:

export class BehaviourState {
  todos: User[] = [];
}

Or by handling null/undefined value within the reducer like the following:

this.setState({ ...this.state, todos: [action.payload.todo, (...this.state.todos || [])] });

  • Related