The initial value of the behavior object is null?

private customer: Subject<Object> = new BehaviorSubject<Object>(null);

setCustomer(id, accountClassCode) {
    this.customer.next({'id': id, 'accountClassCode': accountClassCode});
}

getCustomer() {
    return this.customer.asObservable();
}

I use this part of the code, but I get an error message that the null identifier cannot find. Is there any solution for getting an initial value that is not null?

+6
source share
2 answers

The goal BehaviorSubjectis to provide an initial value. It could be nullor something else. If there is no valid initial value (when the user ID is not yet known), it should not be used.

ReplaySubject(1)provides similar behavior (emits the last value when subscribing), but does not have an initial value until it is set using next.

,

private customer: Subject<Object> = new ReplaySubject<Object>(1);
+13

:

:

@Injectable()
export class MyService {
    customerUpdate$: Observable<any>;

    private customerUpdateSubject = new Subject<any>();

    constructor() {
        this.customerUpdate$ = this.customerUpdateSubject.asObservable();
    }

    updatedCustomer(dataAsParams) {
        this.customerUpdateSubject.next(dataAsParams);
    }
}

MyService .

( ), - :

(, ):

constructor(private myService: MyService) {
        // I'll put this here, it could go anywhere in the component actually
        // We make things happen, Client has been updated
        // We store client data in an object
        this.updatedClient = this.myObjectWithUpdatedClientData;  // Obj or whatever you want to pass as a parameter
        this.myService.updatedCustomer(this.updatedClient);
    }

(, ):

this.myService.customerUpdate$.subscribe((updatedClientData) => {
            // Wow! I received the updated client data
            // Do stuff with this data!
        }
    );

, , . , ? .

, :

Angular 2 Subject/Behavior/ReplaySubject

+1

All Articles