On Wednesday, July 12, 2017 at 10:00:16 AM UTC+2, Tommaso Betti wrote:
>
> How can i return an Observable in the private method if i have to return 
> the Cookie if i don't need to refresh?
> Isn't the same thing that i'm doing here? 
>
>  if (!Cookie.get("access_token")) { 
>     this.getRefresh(Cookie.get("refresh_token"))
>       .subscribe(
>         data => this.saveToken(data),
>         err => alert('Invalid Credentials')
>       );
>
>     cookie = Cookie.get("access_token");
>
>
The problem here is that your "cookie = Cookie.get('access_token')" is 
running *before* this.getRefresh is resolved. You fire off getRefresh, than 
get the access_token, than go on to make that HTTP call params, but your 
getRefresh hasn't yet executed. So in the next loop, your getRefresh goes 
on to fetch the new access_token, *and* you fire off the resource request. 
And than a century later, your http calls start resolving and you get your 
values back.

So the solution, super simplified, is this:

    private getCookieValue() {
      if (this.cookie) {
        return Observable.of(this.cookie);
      }
      return this.http.post(....) // OAuth stuff
        .map((res: Response) => {
          this.cookie = res.json(); // or whatever,
          return this.cookie;
        });
    }

Than your getResource always gets this private method first and chains the 
actual resource call to it. But maybe take a look at things like *Subject,* 
*ReplaySubject* instead of *return Observable.of / this.http.post*. So to 
get a cookie, subscribe to your cookie subject, and the cookie subject 
logic knows that if it has the value already, it will return it without 
making the call again. Basically the same in the crude example above.

Now, depending on how short-lived your user sessions are and how long-lived 
your refresh/access tokens are, you might even make a call to get the fresh 
token *before you bootstrap* the app. You know the bit where you do 
something like this:
  
  platformBrowserDynamic().bootstrapModule(AppModule/*, options*/);

Well, first resolve your access_token, than add a *providers *array there 
with a service that's already configured. But I guess this is specific in 
how long before your users close your tab, or if you have specific 
permissions for certain calls that you have to check for and various things 
so YMMV there.


-- 
You received this message because you are subscribed to the Google Groups 
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to