Jnr
Jnr

Reputation: 1684

Wait for singleton service result before continuing - Angular

I've got a singleton service that just gets the user from an endpoint. The user is then injected into each component where needed. The problem is that there are other functions to execute in the components that are dependent on the user's value (i.e. wait for the user value before executing said functions).

How can I "wait" for a value from the service before continuing? This wait will abviously only be necessary on the initial load of the application, whereas the singlton will already have its instance for subsequent comoponents.

Service Component:

userDetails:IEmployee = {};
constructor(private service: ServiceCaller) {  
this.User().subscribe((x) => {
    this.userDetails = x;
    });
}
public User():Observable<IEmployee> {
    if(this.userDetails == undefined){
        return this.service.get('/some/url')
            .map((resp: IResponse) => {
                return resp.Response
            });
    }
    else {
        //How to return an observable of this.userDetails?
            let obs = Observable.create((observer:any) => {
                observer.next(this.userDetails);
            });
            return obs;
        }
    }
}

Other Components:

this.userService.User().subscribe((x) => {
    //result empty
});

I'm not entirely sure if I'm approaching this correctly, but help will be appreciated.

Upvotes: 1

Views: 297

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

I think you can get away with the call of this.User() in the service's constructor. Just define a variable userDetails in your class as you already have and have your User() method like:

public User():Observable<IEmployee> {
    if(this.userDetails === undefined){
        return this.service.get('/some/url')
            .do((resp: IResponse) => {
                 this.userDetails = resp.Response
            })
            .map((resp: IResponse) => {
                return resp.Response
            });
    }
    else {
        return Observable.of(this.userDetails)
    }
}

Whenever any of the components will subscribe, a call will go to the endpoint if userDetails doesn't already exist.

Upvotes: 1

Related Questions