1

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.

1
  • 3
    this.users is observable. It is potentially asynchronous. It can't be used as if(!this.users) .... It should be this.users.subscribe(users => { if (!users.length) ... }). Commented Oct 11, 2016 at 22:26

1 Answer 1

2

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*/}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that's great. Clearly need to get to grips with Observables rather better. One point is that the if clause did not work. On inspecting Data was an empty array. I used this which worked. if(this.users.length==0){
@Billyhomebase thanks for the feedback. Updated my answer with what I'd do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.