title: Angular2- Getting confused with Observable Catch closure scope
body: <p>Wondering if you can give a little assistance. I appear to be getting myself a bit confused when it comes to using <code>catch</code> with <code>Observable</code>s.</p>
  
  <p>Basically what I'm trying to do is the following:
  When my API returns a 403 error, I want to perform some actions on my <code>TokenStore</code>, namely, delete the local token and mark the user as unauthenticated. The way I'm trying to do this may be wrong, so please do let me know if there's a better way of accomplishing this.</p>
  
  <p>I'm trying to accomplish this with the following code:</p>
  
  <p><strong>APIConnector.service.ts</strong> - a single service for API communication methods</p>
  
  <pre><code>import {Injectable} from 'angular2/core';
  import {Http, Response, Headers, RequestOptions} from 'angular2/http';
  import {Observable}     from 'rxjs/Observable';
  import * as _ from 'lodash';
  import {Logger}     from './logger.service';
  import {TokenStore} from '../stores/token.store';
  
  @Injectable()
  export class APIConnector {
  
      private _apiUrl:string = 'https://api.sb.zerojargon.com/';
      private _token:string = null;
  
      constructor(
          private _http:Http,
          private _logger:Logger,
          private _tokenStore:TokenStore
      ) {}
  
      get(endpoint:String, includes:Array&lt;string&gt;) {
          let includeString = (!_.isUndefined(includes)) ? this._parseIncludes(includes) : '';
          let headers = this._createHeaders();
          let options = new RequestOptions({ headers: headers });
          return this._http.get(this._apiUrl + endpoint + '?include=' + includeString, options);
      }
  
      post(endpoint:String, formData:Object, includes:Array&lt;string&gt;) {
          let includeString = (!_.isUndefined(includes)) ? this._parseIncludes(includes) : '';
          let body = JSON.stringify(formData);
          let headers = this._createHeaders();
          let options = new RequestOptions({ headers: headers });
          return this._http.post(this._apiUrl + endpoint + '?include=' + includeString, body, options);
      }
  
      handleError(error: Response) {
          // log out the user if we get a 401 message
          if (error.json().error.http_code === 401) {
              this._tokenStore.destroy();
          }
          return Observable.throw(error.json().error || 'Server error');
      }
  
      private _parseIncludes(includes:Array&lt;String&gt;) {
          return includes.join();
      }
  
      private _createHeaders() {
          return new Headers({ 'Content-Type': 'application/json', 'Authorization': 'bearer ' + localStorage.getItem('token') });
      }
  }
  </code></pre>
  
  <p>In each of my services which use the APIConnector, I have catch methods on the <code>Observable</code>s, to run the <code>handleError</code> closure. e.g.</p>
  
  <pre><code>public createEvent(event:Object) {
      let endpoint = this._endpoint;
      return this._apiConnector.post('clients/'+this.client+'/events', event, this._defaultIncludes)
          .map(res =&gt; {
              return this._transformer.map('event', &lt;Object[]&gt;res.json());
          })
          .catch(this._apiConnector.handleError);
  }
  </code></pre>
  
  <p>However, this gives the following error:</p>
  
  <blockquote>
    <p>EXCEPTION: TypeError: Cannot read property 'destroy' of undefined</p>
  </blockquote>
  
  <p>Presumably this is because handleError is a closure. I'm unsure of the best way to deal with this, though.</p>
  
  <p>Any thoughts would be greatly appreciated</p>