title: angular2 - set interval to check jwt token validity
body: <p>I'm trying to create a standalone service that is only responsible for checking whether a token is expired or not.   </p>
  
  <p>Normally I would just start an Interval and test the JWT token using <code>tokenNotExpired()</code> or <code>JwtHelper.isTokenExpired()</code>. But with Angular2 I'm not so sure as how I'm I supposed to handle this kind of stuff. It can't be that easy, right? :) </p>
  
  <p>All the token validity is currently being performed in home.component, but that's exactly what I'm trying to avoid and hence intend to separate this concern into a standalone service. </p>
  
  <p>The below is just an hypothetical example as how it might be working.</p>
  
  <ul>
  <li>user logs-in</li>
  <li>home component initializes</li>
  <li>subscribe to session-check.service.validate()</li>
  <li>check the output of the session validation check</li>
  </ul>
  
  <p>The problem here is, should I use Observable or just start a simple Interval? What's the best and most proper concept to handle periodical calls inside a component?</p>
  
  <p><strong>home.component.ts</strong></p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { Http } from '@angular/http';
  import { Router } from '@angular/router';
  import { SessionCheckService } from '../services/session-check.service';
  
  
  @Component({
    moduleId: module.id,
    selector: 'home',
    templateUrl: '../templates/home.component.html',
    styleUrls: [ '../styles/home.component.css' ],
    providers: [ SessionCheckService ]
  })
  export class HomeComponent implements OnInit {
    private jwt: string;
    private decodedJwt: string;
  
    constructor (
      private router: Router, 
      private http: Http
      private sessionCheckService: SessionCheckService
     // private jwtHelper: JwtHelper
    ) {}
  
    ngOnInit(): void {
      this.jwt = localStorage.getItem('id_token');
      // this.decodedJwt = null; //this.jwt &amp;&amp; this.jwtHelper.decodeToken(this.jwt);
      var s = this.sessionCheckService.validate( this.jwt );
      s.subscribe((res) =&gt; {
          console.log( res )
      })
    }
  
    public logout() {
      localStorage.removeItem('id_token');
      this.router.navigate(['login']);
    }
  }
  </code></pre>
  
  <p><strong>session-check.service.ts</strong></p>
  
  <pre><code>import { JwtHelper } from 'angular2-jwt';
  import { Injectable } from '@angular/core';
  //import { AuthHttp, JwtHelper } from 'angular2-jwt';
  
  import { Observable } from 'rxjs';
  import 'rxjs/add/operator/toPromise';
  
  @Injectable()
  export class SessionCheckService {
      constructor( private jwtH:  JwtHelper ){};
  
      validate( token:string ): Observable&lt; boolean &gt;{
          return new Observable.interval(500).flatMap( () =&gt; {
              this.jwtH.isTokenExpired( token )
          } );
      }
  }
  </code></pre>