Angular2: convert array to Observable : <p>I have a component that gets the data from a service via http, the problem is that I don't want to hit the API backend every time I show this component. I want my service to check if the data is in memory, if it is, return an observable with the array in memory, and if not, make the http request.</p>

<p>My component</p>

<pre><code>import {Component, OnInit } from 'angular2/core';
import {Router} from 'angular2/router';

import {Contact} from './contact';
import {ContactService} from './contact.service';

@Component({
  selector: 'contacts',
  templateUrl: 'app/contacts/contacts.component.html'
})
export class ContactsComponent implements OnInit {

  contacts: Contact[];
  errorMessage: string;

  constructor(
    private router: Router,
    private contactService: ContactService) { }

  ngOnInit() {
    this.getContacts();
  }

  getContacts() {
    this.contactService.getContacts()
                       .subscribe(
                         contacts =&gt; this.contacts = contacts,
                         error =&gt;  this.errorMessage = &lt;any&gt;error
                       );
  }
}
</code></pre>

<p>My service</p>

<pre><code>import {Injectable} from 'angular2/core';
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Contact} from './contact';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ContactService {

  private contacts: Array&lt;Contact&gt; = null;

  constructor (private http: Http) {

  }

  getContacts() {
    // Check first if contacts == null
    // if not, return Observable(this.contacts)? &lt;-- How to?

    return this.http.get(url)
                    .map(res =&gt; &lt;Contact[]&gt; res.json())
                    .do(contacts =&gt; {
                      this.contacts = contacts;
                      console.log(contacts);
                    }) // eyeball results in the console
                    .catch(this.handleError);
  }


  private handleError (error: Response) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}
</code></pre>
