Handling expired cookie in Angular 2
<p>I am experimenting with Angular 2 and trying to use document.cookie as my access-token storage.</p>

<p>What I have done is I set a cookie with an accesstoken &amp; expiration of 30 mins. Now the application will set the cookie on load so subsequent api process handle pretty well till 30 mins. My problem is i want to check if cookies is expired and then fetch new accesstoken set it to the cookie and call respective method.</p>

<p>Here's my code</p>

<pre><code>import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable, Operator} from 'rxjs/Rx';

import { AccessToken } from './access-token.service';


@Injectable()
export class DataService {  

  constructor(
      private _accessToken : AccessToken,
      private _http: Http
  ) {}

  request(url:string){
      var token = this._accessToken.readCookie();
      return this._http.get(url,{
          headers : new Headers({
              "Authorization" : "Bearer " + token
          })
      })
          .map(data =&gt; data.json().result)
          .catch(this._handleError)

  }

  fetchData(dataurl:string){
     var token = this._accessToken.readCookie();

     if(!token){        
        this._accessToken.getToken()
            .subscribe(
                response =&gt; {
                    this._accessToken.setCookie(response);                  
                }
            )
            // I want to call this.request() after the accesstoken has been set to the document.cookie

      } else {
            return this.request(dataurl)
      }
  }

  getAllProducts(){
      return this.fetchData('https://localhost/api/products');
  }


  private _handleError (error: Response) {
      console.error(error);
      return Observable.throw(error.json().error || 'Server error');
  }
}
</code></pre>

<p>The <code>this._accessToken.getToken()</code> method make a http.post request to an endpoint and gets an accesstoken.
The <code>this._accessToken.setCookie()</code> method then sets a document.cookie with the accesstoken and expiration time of 30 mins.</p>

<p>I'm not sure how i go about sequencing the <code>fetchData()</code> method incase of cookie expiration so that it first gets accesstoken sets it to cookie then only calls the <code>request</code> method.</p>

<p>Thanks</p>