title: Getting data from a shared service angular2
body: <p>What I want to achieve is: uploading an image from the first component using the uploaderService. After successful uploading, my server is sending a key as HTTP
  response which I am being able to access/print from the first component. After successful uploading, the first componet is redirecting to second component. Now,
  I want to access/print/use the value of the key from the service (that's already accessible to the first component) in the second component.</p>
  
  <p>What I tried is: Making the service a shared service which is Injectable. So if I import the service and initiate it with a constructor it should have the same
  instance of the service the first component is using. So the value I am getting in the success callback in the first component should be accessible to my second
  component somehow. Here are my codes.</p>
  
  <p>nb: I have provided the service to the ngModule. I guess it's now shared enough, and fully accessible from both of my components. I am successfully using the service and getting the key in the first component. But not sure how to get it in the second component. The fat arrow functions
  are confusing me. Shouldn't I be able to get the value of a variable x, from a function A in the service by calling it in the component like:</p>
  
  <blockquote>
    <p>someassignablevariable = this.service.x;</p>
  </blockquote>
  
  <p>My First Component:</p>
  
  <pre><code>import {Component, Output} from '@angular/core';
  import { Uploader } from '../services/uploader';
  import { MyUploadItem } from '../services/my-upload-item';
  import {Router} from "@angular/router";
  
  @Component({
      template: `
  //tempate codes
      `
  })
  
  export class FirstComponent {
      constructor(public uploaderService: Uploader, private _router: Router) { }
  
      public pushKey: String;
  
      submit() {
          let uploadFile = (&lt;HTMLInputElement&gt;window.document.getElementById('sampleFile')).files[0];
  
  
          let myUploadItem = new MyUploadItem(uploadFile);
  
          this.uploaderService.onSuccessUpload = (item, response, status, headers) =&gt; {
              // success callback
              this.pushKey = response.toString();
              console.log('Push Key:'+ response.toString())
              this._router.navigate(['second-component']);
          };
          this.uploaderService.onErrorUpload = (item, response, status, headers) =&gt; {
              // error callback
  
              console.log(response.toString());
          };
          this.uploaderService.onCompleteUpload = (item, response, status, headers) =&gt; {
              // complete callback, called regardless of success or failure
              console.log(response.toString());
          };
          this.uploaderService.onProgressUpload = (item, percentComplete) =&gt; {
              // progress callback
              console.log(percentComplete);
          };
          this.uploaderService.upload(myUploadItem);
      }
  }
  </code></pre>
  
  <p>My Second Component:</p>
  
  <pre><code>import {Component, OnInit} from '@angular/core';
  import {Uploader} from "../services/uploader";
  
  @Component({
      template: `
      ....
      &lt;p&gt;Push Key: {{pushKey}}&lt;/p&gt;               
      ....
      `
  })
  
  
  export class SecondComponent{
  
      constructor(public uploaderService: Uploader) { }
  
      pushKey: String;
  
      ngOnInit(){this.getKey()}
  
          getKey() {
  
              this.uploaderService.onSuccessUpload = (item, response, status, headers) =&gt; {
                  // success callback
                  this.pushKey = response.toString();
                  console.log('Push Key:' + this.pushKey);
              };
              return this.pushKey;
          }
  }
  </code></pre>
  
  <p>My Service:</p>
  
  <pre><code>import { Injectable }  from '@angular/core';
  import { UploadItem }  from './upload-item';
  
  @Injectable()
  export class Uploader {
      onProgressUpload = (item: UploadItem, progress: number) =&gt; {};
      onCompleteUpload = (item: UploadItem, response: any, status: any, headers: any) =&gt; {};
      onSuccessUpload = (item: UploadItem, response: any, status: any, headers: any) =&gt; {};
      onErrorUpload = (item: UploadItem, response: any, status: any, headers: any) =&gt; {};
      onCancelUpload = (item: UploadItem, response: any, status: any, headers: any) =&gt; {};
  
      constructor() { }
  
      upload(item: UploadItem) {
          if(this.isHTML5()) {
              this.xhrTransport(item);
          } else {
              this.onErrorUpload(item, 'Unsupported browser.', null, null);
          }
      }
  
      private isHTML5(): boolean {
          return !!((&lt;any&gt;window).File &amp;&amp; (&lt;any&gt;window).FormData);
      }
  
      private xhrTransport(item: UploadItem) {
          let xhr  = new (&lt;any&gt;window).XMLHttpRequest();
          let form = new (&lt;any&gt;window).FormData();
  
          this.forEach(item.formData, (key: string, value: any) =&gt; {
              form.append(key, value);
          });
  
          form.append(item.alias, item.file, item.file.name);
  
  
          xhr.upload.onprogress = (event: any) =&gt; {
              let progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
              this.onProgressUpload(item, progress);
          };
  
          xhr.onload = () =&gt; {
              let headers = this.parseHeaders(xhr.getAllResponseHeaders());
              let response = this.parseResponse(headers['Content-Type'], xhr.response);
              if(this.isSuccessStatus(xhr.status)) {
                  this.onSuccessUpload(item, response, xhr.status, headers);
              } else {
                  this.onErrorUpload(item, response, xhr.status, headers);
              }
              this.onCompleteUpload(item, response, xhr.status, headers);
          };
  
          xhr.onerror = () =&gt; {
              let headers = this.parseHeaders(xhr.getAllResponseHeaders());
              let response = this.parseResponse(headers['Content-Type'], xhr.response);
              this.onErrorUpload(item, response, xhr.status, headers);
              this.onCompleteUpload(item, response, xhr.status, headers);
          };
  
          xhr.onabort = () =&gt; {
              let headers = this.parseHeaders(xhr.getAllResponseHeaders());
              let response = this.parseResponse(headers['Content-Type'], xhr.response);
              this.onCancelUpload(item, response, xhr.status, headers);
              this.onCompleteUpload(item, response, xhr.status, headers);
          };
  
          xhr.open(item.method, item.url, true);
  
          xhr.withCredentials = item.withCredentials;
  
          this.forEach(item.headers, (name: string, value: string) =&gt; {
              xhr.setRequestHeader(name, value);
          });
  
          xhr.send(form);
      }
  
      private isSuccessStatus(status: number) {
          return (status &gt;= 200 &amp;&amp; status &lt; 300) || status === 304;
      }
  
      private forEach(obj: any, callback: any) {
          for (var i in obj) {
              if (obj.hasOwnProperty(i)) {
                  callback(i, obj[i]);
              }
          }
      }
  
      private parseHeaders(headers: string) {
          let dict = {};
          let lines = headers.split('\n');
          for (let i = 0; i &lt; lines.length; i++) {
              let entry = lines[i].split(': ');
              if(entry.length &gt; 1) {
                  dict[entry[0]] = entry[1];
              }
          }
          return dict;
      }
  
      private parseResponse(contentType: string, response: string) {
          let parsed = response;
          if(contentType &amp;&amp; contentType.indexOf('application/json') === 0) {
              try {
                  parsed = JSON.parse(response);
              } catch(e) {
              }
          }
          return parsed;
      }
  
  }
  </code></pre>