jonnie
jonnie

Reputation: 12710

Correct way to retrieve single item rxjs in Angular2

Firstly I am new to Angular2 Rxjs (and observables in general) and ES6/ES2015 so the issue may be as result of any of these.

I have a Service in Angular 2 that creates a store and has both a loadAll and load single function as well as an exposed getter. Its currently hooked up to dummy data but will eventually be a http request (commented out below)

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { Http, Response } from '@angular/http';

export interface Article {
  id: number;
  title: string;
  content: string;
  author: string;
}

@Injectable()
export class ArticleService {
  private _articles$: Subject<Article[]>;
  private baseUrl: string;
  private dataStore: {
    articles: Article[]
  };

  private dummyData = [
      {
        id: 1,
        title: 'Title 1',
        content: 'content 1',
        author: 'author 1'
      },
      {
        id:2,
        title: 'Title 2',
        content: 'content 2',
        author: 'author 1'
      }
    ];

  constructor(private http: Http) {
    this.baseUrl = 'http://localhost:3000'
    this.dataStore = { articles: [] };
    this._articles$ = <Subject<Article[]>>new Subject();
  }
  get articles$(){
    return this._articles$.asObservable();
  }

  loadAll(){
    //Observable.fromPromise(Promise.resolve(this.dummyData))
    this.http.get(`${this.baseUrl}/articles`)
      // map for actual http requests
    .map(response => response.json())
    .subscribe(data => {
      //debugger;
      this.dataStore.articles = data;
       // Push a new copy of our article list to all Subscribers.
      this._articles$.next(this.dataStore.articles)
    }, error => console.log('Could not load Articles'));
  }

  load(id: any) {
    Observable.fromPromise(Promise.resolve(this.dummyData[id-1]))
    //this.http.get(`${this.baseUrl}/articles/${id}`)
      // map for actual http requests
    //.map(response => response.json())
    .subscribe(data => {
      let notFound = true;

      this.dataStore.articles.forEach((item, index) => {
        if (item.id === data.id) {
          this.dataStore.articles[index] = data;
          notFound = false;
        }
      });

      if (notFound) {
        this.dataStore.articles.push(data);
      }

      this._articles$.next(this.dataStore.articles);
    }, error => console.log('Could not load todo.'));
  }
}

I am then able to display the list as expected in the component:

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { ArticleService } from '../shared';

@Component({
  moduleId: module.id,
  selector: 'app-home',
  directives :[
    ROUTER_DIRECTIVES
  ],
  providers:[
    ArticleService
  ],
  template: `
    <h1>My List</h1>
    <ul>
      <li *ngFor="let item of items$ | async; let i = index">
        <a [routerLink]="['/article', item.id]" > {{item.title}} </a>
      </li>
    </ul>
  `,
  styleUrls: ['home.component.css']
})
export class HomeComponent implements OnInit {
  items$ = null;
  constructor(private articleService: ArticleService) {
    this.articleService = articleService;
  }

  ngOnInit() {
    this.items$ = this.articleService.articles$;
    this.articleService.loadAll();
  }
}

but how can I display a single Item in the Item component, this is what I have tried:

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES, ActivatedRoute, Router } from '@angular/router';
import { ArticleService } from '../shared';

@Component({
  moduleId: module.id,
  selector: 'app-article',
  providers: [
    ArticleService
  ],
  template: `
      <h1>{{item$.title}}</h1>
      <p>{{item$.content}}</p>
  `,
  styleUrls: ['article.component.css']
})
export class ArticleComponent implements OnInit {
  private sub: any;
  private id: number;
  private item$ = null;
  //  private all = null;

  constructor(private route: ActivatedRoute,
    private router: Router, private articleService: ArticleService) {
    this.route = route;
    this.articleService = articleService;
  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      let id = +params['id']; // (+) converts string 'id' to a number
      //this.service.getHero(id).then(hero => this.hero = hero);
      this.id = id
    });

    this.articleService.load(this.id);
    //this.all = this.articleService.articles$;
    this.articleService.articles$
    .reduce((c, n) => {
      return n["id"] === this.id ? n : c;
     })
     .subscribe(data => {
        this.item$ = JSON.stringify(data);
      });
  }

}

I have also tried filtering:

this.articleService.articles$
    .filter((n) => {
        n["id"] === this.id ;

       })
      .subscribe(data => {
        this.item$ = data;
      });

which throws error Argument of type '(n: Article[]) => void' is not assignable to parameter of type '(value: Article[], index: number) => boolean'

and selecting a single item:

.subscribe(data => {
    this.item$ = data[0];
});

the most confusing things are if I do this.item$ = JSON.stringify(data[0]); it will display as a normal string when I reference {{item$}} in template: {"id":1,"title":"Title 1","content":"content 1","author":"author 1"} and as [object Object] without the stringify but when I reference {{item$.id}} or any other attributes I get the error TypeError: Cannot read property 'id' of null

Other issues I noticed that may be related include:

Upvotes: 0

Views: 1003

Answers (1)

Andrei Zhytkevich
Andrei Zhytkevich

Reputation: 8099

Try Elvis operator ?. inside interpolation.

{{item$?.id}}

In case item$ is falsy (undefined, null, etc.) it won't access id member.

item$ will be null until you get response.

Note: You can actually stop debugger inside filter and similar functions. Just make it multi-line. Also, you can put a console message when the arrow function is multilined.

Upvotes: 4

Related Questions