从 Angular observable 中移除 null 或 undefined

Removing null or undefined from Angular observable

我正在使用 BehaviourSubject 进行 Angular 状态管理,但是在将数据推送到存储时正在将 undefined 值添加到对象的末尾(创建另一个 undefined 价值)。任何人都可以建议删除的方法吗?

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

以下是示例片段,

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

最后按以下方式添加数据,

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

因为您还没有为待办事项定义任何默认值。它显示未定义。

试试这个:

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

发生这种情况是因为 todos 的初始值是 undefined,因此您需要在 BehaviourState class 中为其分配一个初始值,例如:

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

或者通过处理 reducer 中的 null/undefined 值,如下所示:

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