Created
March 10, 2018 04:38
-
-
Save rahulsahay19/4736aac214db16d6f866e9828737ee36 to your computer and use it in GitHub Desktop.
app.component.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; | |
import * as _ from 'lodash'; | |
import { Post } from './post'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/add/operator/catch'; | |
import 'rxjs/add/operator/retry'; | |
import 'rxjs/add/observable/of'; | |
import { retry } from 'rxjs/operator/retry'; | |
import 'rxjs/add/observable/forkJoin'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent implements OnInit { | |
/** | |
* | |
*/ | |
constructor(private http: HttpClient) { | |
} | |
title = 'app'; | |
readonly ROOT_URL= 'https://jsonplaceholder.typicode.com'; | |
posts:Observable<Post[]>; | |
newPost: Observable<any>; | |
parallelRequests() { | |
const parallel = Observable.forkJoin( | |
this.http.get(this.ROOT_URL + '/posts?userId=7'), | |
this.http.get(this.ROOT_URL + '/posts?userId=3'), | |
); | |
parallel.subscribe( | |
values => { | |
console.log("Combined Values", values) | |
} | |
); | |
} | |
getPosts(){ | |
let params = new HttpParams().set('userId', '7'); | |
let headers = new HttpHeaders().set('Authorization', 'auth-key'); | |
this.posts =this.http.get<Post[]>(this.ROOT_URL + '/posts', { headers }) | |
} | |
submitPost(){ | |
const data:Post = { | |
id:null, | |
userId :7, | |
title: 'New Post', | |
body: 'Hello HTTP Client!' | |
} | |
// this.newPost = this.http.post<Post>(this.ROOT_URL + '/posts', data) | |
// .map(post => post.title) | |
// Doesn't exist | |
this.newPost = this.http.post(this.ROOT_URL + '/rahul', data) | |
// tells rxjs to retry the request to 5 times | |
.retry(5) | |
// If it continues to fail, will catch it and return console.log as observable | |
.catch(err => { | |
console.log(err) | |
return Observable.of(err) | |
}); | |
} | |
ngOnInit() { | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment