Skip to content

Instantly share code, notes, and snippets.

@miloszpp
Created November 24, 2017 21:57
Show Gist options
  • Save miloszpp/d2eb04573a392e1c538c74c6920b3dee to your computer and use it in GitHub Desktop.
Save miloszpp/d2eb04573a392e1c538c74c6920b3dee to your computer and use it in GitHub Desktop.
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from '../model';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import "rxjs/add/observable/combineLatest";
import "rxjs/add/observable/merge";
import "rxjs/add/operator/map";
import "rxjs/add/operator/switchMap";
@Component({
selector: 'app-example-rx-fp',
template: `
<button (click)="goodCommentsClickStream.next()">Fetch good comments</button>
<button (click)="badCommentsClickStream.next()">Fetch bad comments</button>
<pre>{{ (comments | async) | json }}</pre>
`,
styles: []
})
export class ExampleRxFpComponent implements OnInit {
private url = "https://jsonplaceholder.typicode.com/posts";
comments: Observable<Comment[]>;
goodCommentsClickStream: Observable<any> = new Subject<any>();
badCommentsClickStream: Observable<any> = new Subject<any>();
constructor(private httpClient: HttpClient) { }
ngOnInit() {
const dataStream = this.httpClient.get<Post[]>(this.url);
const goodComments = this.goodCommentsClickStream.switchMap(
() => this.httpClient.get<Comment[]>(this.goodCommentsUrl)
);
const badComments = this.badCommentsClickStream.switchMap(
() => this.httpClient.get<Comment[]>(this.badCommentsUrl)
);
this.comments = Observable.merge(
goodComments,
badComments
);
}
private goodCommentsUrl = "https://jsonplaceholder.typicode.com/comments?postId=1";
private badCommentsUrl = "https://jsonplaceholder.typicode.com/comments?postId=2";
}
@Pawel-Durzynski
Copy link

Than you for an example for ngPoland 2017.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment