I am learning Angular 2 and RxJS at the moment and feel that this is probably the simplest question there is. I am using the Store to save 'users' to. I want to test to see if this is empty or not from the Typescript side rather than in the Angular template.
Below are the pertinent lines of code.
public users: Observable<User[]>;
public store: Store<AppState>;
this.users = this.store.select(state => state.user);
if(!this.users) {
//DO THIS
}
I have tried length, == null, == undefined and can't find how to test for this seemingly basic state. Any help appreciated.
Note that saving and retrieving users to the store is working correctly.
Assuming the Store
works as you indicate, it returns an Observable. So what you receive (this.users
) is not actually the store value, but rather a stream that will output that value.
As a consequence, to test whether the value is empty, you don't test the stream itself. Rather, you subscribe to the stream and observe what comes out:
public users: User[];
// subscribing will actually trigger the fetch for user data
this.store.select(state => state.user)
.subscribe(data => this.onUsersEmitted(data));
// executed once user data arrives from the store
public onUsersEmitted(data:User[]){
this.users = data;
if(!data || !data.length){ /*empty data arrived*/}
}