1

I want to resolve an observable to it's underlying type. Yes, I am aware I should NOT be doing so, but at the moment I would like to test something without Fixing My architecture, and I would like to know if its possible.

This is a function in the base provider to call a GET request

getByRoute(url: string): Observable<T> {
    return this.http.get(url).map(res => <T>res.json());
}

I had an only class returning a concrete object with just an Id on it. //public currentUser = { id: 1 };

But now I'm trying to implement my provider to lazy load the current user, I don't have time right now to switch everything to use an observable, but I would like to know my other code works.

private _user: User;
get currentUser(): User {
    if (this._user == null) {
        this._user = this.getLoggedInUser();
    }
    return this._user;
}
set currentUser(user: User) {
    this._user = user;
}

constructor(public usersProvider: Users) {
}

getLoggedInUser(): User {
    return this.usersProvider.getByRoute(URL).single();
};

How can I Resolve my Observable to get the entity?

johnny 5
  • 19,893
  • 50
  • 121
  • 195

1 Answers1

1

You will need to subscribe to the observable and then assign it to the property on your class.

this.usersProvider.getByRoute(URL).subscribe(next => {
  this.currentUser = next;
});

Note that you will need to handle cleanup of this subscription on your own! (this thread will help with that: Angular/RxJs When should I unsubscribe from `Subscription`)

Also, you can't really "resolve" an Observable -- it is not a Promise! Check out this thread for more on that: Angular - Promise vs Observable

vince
  • 7,808
  • 3
  • 34
  • 41
  • Yes, but how will subscribing help? If someone requests current user in my code it will return before the request comes back – johnny 5 Jan 27 '18 at 18:45
  • Hmm I'm not sure if what I'm trying to do is even possible, I'll ask a new question since this resolve most of mine – johnny 5 Jan 27 '18 at 19:56