title: Angular 2 using ngrx + RxJS subscribing on multiple components/routes to populate store
body: <p>I'm currently building an Angular 2 app using both Redux (ngrx) and RxJS (mainly for learning purposes), however it's still a bit (to say the least) confusing to me.</p>
  
  <p>I'm trying to implement a "/projects" route, as well as a "/projects/:id" route. On both of these the behaviour is that I make an HTTP request to fetch the required data.</p>
  
  <p>Currently, if I navigate to "projects" (either by URL or ajax call via navigation) it will get all 15 or so projects back from the server and add them to the "projects" store on Redux. Now, if I currently try to get in from a specific project (from the browser's searchbar -> "localhost:3000/projects/2", for example) it will only fetch the one, which is what I want and place it in the store, however if I then navigate to the "projects" section from there, it will only print the one project that is located in the store.</p>
  
  <p>What I want to accomplish is the following:</p>
  
  <ul>
  <li>If I get into "/projects" first, then fetch and place all results in store.</li>
  <li>If the above case is met and I navigate to a specific project from there, using a link tag, I want to check the store for the item which has that specific id and return it.</li>
  <li>If I get in from "/projects/:id" directly, I want to fetch that specific project only and place it in the store.</li>
  <li>If the immediately above point happens, I want to be able to navigate to "/projects", via my menu or any other link, fetch all items and update my "projects" store with all the items (not just the one that already existed from the previous point)</li>
  <li>Any other logic scenario that I might be missing respecting the above</li>
  </ul>
  
  <p>I want to accomplish this on an efficient, performant and elegant way.</p>
  
  <p>I am currently, I believe, subscribed to the same Observable from at least two places and I do not believe that is the right approach. On top of that, I'm still not able to get the results I want if I get in from the "/projects:/id" route first and then navigate to the "/projects" route.</p>
  
  <p>Here's the code that I consider relevant:</p>
  
  <p><strong>projects.directive.ts</strong></p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { ProjectsService } from '../shared/services/projects.service';
  import { Observable } from 'rxjs/Observable';
  import { Project } from '../../models/project.model';
  
  @Component({
    selector: 'projects',
    templateUrl: './projects.html'
  })
  export class Projects implements OnInit {
    private projects$: Observable&lt;Project[]&gt;
  
    constructor(private projectsService: ProjectsService) {}
  
    ngOnInit() {
      this.projectsService.findProjects();
    }
  }
  </code></pre>
  
  <p><strong>projectOne.directive.ts</strong></p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { Params, ActivatedRoute } from '@angular/router';
  import { Observable } from 'rxjs/Observable';
  import { ProjectsService } from '../../shared/services/projects.service';
  import { Project } from '../../../models/project.model';
  
  @Component({
    selector: 'projectOne',
    templateUrl: './projectOne.html'
  })
  export class ProjectOneComponent implements OnInit {
    private projects$: Observable&lt;Project[]&gt;
  
    constructor(private route: ActivatedRoute, private projectsService: ProjectsService) {}
  
    ngOnInit() {
      this.route.params.subscribe((params: Params) =&gt; {
        this.projectsService.findProjects(params['id'])
      });
    }
  }
  </code></pre>
  
  <p>*Some things to note here: I am subscribing to <em>this.route.params</em>, which subscribes to yet another Observable, do I need to flatten that at all or nay? The concept still beats me</p>
  
  <p><strong>projects.html</strong></p>
  
  <pre><code>&lt;section&gt;
    &lt;article *ngFor="let project of projectsService.projects$ | async"&gt;
      &lt;p&gt;{{project?._id}}&lt;/p&gt;
      &lt;p&gt;{{project?.name}}&lt;/p&gt;
      &lt;img src="{{project?.img}}" /&gt;
      &lt;a routerLink="{{project?._id}}"&gt;See more&lt;/a&gt;
    &lt;/article&gt;
  &lt;/section&gt;
  </code></pre>
  
  <p>*Here I'd like to make note that I'm also using <em>projectsService.projects$ | async</em> to print the results on the iteration which I'm quite positive also affects...</p>
  
  <p><strong>projects.service.ts</strong></p>
  
  <pre><code>import { Http } from '@angular/http';
  import { Injectable } from '@angular/core';
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/map';
  import { Store } from '@ngrx/store';
  import { Project } from '../../../models/project.model';
  import { AppStore } from '../../app.store';
  import { ADD_PROJECTS } from '../../../reducers/projects.reducer';
  
  @Injectable()
   export class ProjectsService {
    public projects$: Observable&lt;Project[]&gt;;
  
    constructor(private _http: Http, private store: Store&lt;AppStore&gt;){
      this.projects$ = store.select&lt;Project[]&gt;('projects');
    }
  
    fetchProjects(id) {
      return this._http.get(`/api/projects?id=${id}`)
      .map(res =&gt; res.json())
      .map(({projectsList}) =&gt; ({ type: ADD_PROJECTS, payload: projectsList }))
      .subscribe(action =&gt; this.store.dispatch(action));
    }
  
    findProjects(id: Number = 0) {
      this.projects$.subscribe(projects =&gt; {
        if (projects.length) {
          if (projects.length === 1) {
            return this.fetchProjects();
          }
        } else {
         return this.fetchProjects(id ? id : '')
        }
      })
    }
  }
  </code></pre>
  
  <p>*I'm guessing every time I call that "findProjects" function I'm subscribing to the Observable. No good, huh?</p>
  
  <p>*Also, with this current setup whenever I go directly into "/projects/:id" it seems to be executing the fetchProjects function twice (I figured that much by console logging). Essentially, the <em>this.projects$</em> subscription within findProjects jumps in and fetches the project with the corresponding id, but then it goes in again and fetches every other project and lastly it just "goes away"? 
  Why is it calling itself, or where is the second call coming from?</p>
  
  <p><strong>projects.reducer.ts</strong></p>
  
  <pre><code>import { Project } from '../models/project.model';
  import { ActionReducer, Action } from '@ngrx/store';
  
  export const ADD_PROJECTS = 'ADD_PROJECTS';
  
  export const projects: ActionReducer&lt;Project[]&gt; = (state: Project[] = [], action: Action) =&gt; {
    switch (action.type) {
      case ADD_PROJECTS:
        return action.payload;
      default:
        return state;
    }
  };
  </code></pre>
  
  <p>*This is all the reducer has for the time being because I'm still super stuck on the rest.</p>
  
  <p>Anyways, I'd like to thank you all in advance. If anything is not clear at all or you need any more info, please let me know. I know this covers more than just one thing and might be super easy or not at all but I'm really eager to get as much help as possible because I'm really stuck here... Thanks again!</p>