Skip to content

Instantly share code, notes, and snippets.

@jhades
Last active January 21, 2020 10:45
Show Gist options
  • Save jhades/9c439200c392d4e32c5b28c1c8052d02 to your computer and use it in GitHub Desktop.
Save jhades/9c439200c392d4e32c5b28c1c8052d02 to your computer and use it in GitHub Desktop.
Angular HTTP
import {HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {HttpClient} from "@angular/common/http";
import * as _ from 'lodash';
interface Course {
description: string;
courseListIcon:string;
iconUrl:string;
longDescription:string;
url:string;
}
@Component({
selector: 'app-root',
template: `
<ul *ngIf="courses$ | async as courses else noData">
<li *ngFor="let course of courses">
{{course.description}}
</li>
</ul>
<ng-template #noData>No Data Available</ng-template>
`})
export class AppComponent implements OnInit {
courses$: Observable<Course[]>;
constructor(private http:HttpClient) {
}
ngOnInit() {
this.courses$ = this.http
.get<Course[]>("/courses.json")
.map(data => _.values(data))
.do(console.log);
}
}
import {HttpParams} from "@angular/common/http";
const params = new HttpParams()
.set('orderBy', '"$key"')
.set('limitToFirst', "1");
this.courses$ = this.http
.get("/courses.json", {params})
.do(console.log)
.map(data => _.values(data))
const params = new HttpParams();
params.set('orderBy', '"$key"')
params.set('limitToFirst', "1");
const params = new HttpParams({
fromString: 'orderBy="$key"&limitToFirst=1'
});
const params = new HttpParams({
fromString: 'orderBy="$key"&limitToFirst=1'
});
this.courses$ = this.http
.request(
"GET",
"/courses.json",
{
responseType:"json",
params
})
.do(console.log)
.map(data => _.values(data));
const headers = new HttpHeaders()
.set("X-CustomHeader", "custom header value");
this.courses$ = this.http
.get(
"/courses.json",
{headers})
.do(console.log)
.map(data => _.values(data));
httpPutExample() {
const headers = new HttpHeaders()
.set("Content-Type", "application/json");
this.http.put("/courses/-KgVwECOnlc-LHb_B0cQ.json",
{
"courseListIcon": ".../main-page-logo-small-hat.png",
"description": "Angular Tutorial For Beginners TEST",
"iconUrl": ".../angular2-for-beginners.jpg",
"longDescription": "...",
"url": "new-value-for-url"
},
{headers})
.subscribe(
val => {
console.log("PUT call successful value returned in body",
val);
},
response => {
console.log("PUT call in error", response);
},
() => {
console.log("The PUT observable is now completed.");
}
);
}
httpPatchExample() {
this.http.patch("/courses/-KgVwECOnlc-LHb_B0cQ.json",
{
"description": "Angular Tutorial For Beginners PATCH TEST",
})
.subscribe(
(val) => {
console.log("PATCH call successful value returned in body",
val);
},
response => {
console.log("PATCH call in error", response);
},
() => {
console.log("The PATCH observable is now completed.");
});
}
httpDeleteExample() {
this.http.delete("/courses/-KgVwECOnlc-LHb_B0cQ.json")
.subscribe(
(val) => {
console.log("DELETE call successful value returned in body",
val);
},
response => {
console.log("DELETE call in error", response);
},
() => {
console.log("The DELETE observable is now completed.");
});
}
httpPostExample() {
this.http.post("/courses/-KgVwECOnlc-LHb_B0cQ.json",
{
"courseListIcon": "...",
"description": "TEST",
"iconUrl": "..",
"longDescription": "...",
"url": "new-url"
})
.subscribe(
(val) => {
console.log("POST call successful value returned in body",
val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
}
duplicateRequestsExample() {
const httpGet$ = this.http
.get("/courses.json")
.map(data => _.values(data));
httpGet$.subscribe(
(val) => console.log("logging GET value", val)
);
this.courses$ = httpGet$;
}
// put this next to the other RxJs operator imports
import 'rxjs/add/operator/shareReplay';
const httpGet$ = this.http
.get("/courses.json")
.map(data => _.values(data))
.shareReplay();
import 'rxjs/add/observable/forkJoin';
parallelRequests() {
const parallel$ = Observable.forkJoin(
this.http.get('/courses/-KgVwEBq5wbFnjj7O8Fp.json'),
this.http.get('/courses/-KgVwECOnlc-LHb_B0cQ.json')
);
parallel$.subscribe(
values => {
console.log("all values", values)
}
);
}
sequentialRequests() {
const sequence$ = this.http.get<Course>(
'/courses/-KgVwEBq5wbFnjj7O8Fp.json')
.switchMap(course => {
course.description+= ' - TEST ';
return this.http.put(
'/courses/-KgVwEBq5wbFnjj7O8Fp.json',
course)
});
sequence$.subscribe();
}
sequentialRequests() {
const sequence$ = this.http.get<Course>(
'/courses/-KgVwEBq5wbFnjj7O8Fp.json')
.switchMap(course => {
course.description+= ' - TEST ';
return this.http.put('/courses/-KgVwEBq5wbFnjj7O8Fp.json', course)
},
(firstHTTPResult, secondHTTPResult) =>
[firstHTTPResult, secondHTTPResult]);
sequence$.subscribe(
values => console.log("result observable ", values)
);
}
throwError() {
this.http
.get("/api/simulate-error")
.catch( error => {
// here we can show an error message to the user,
// for example via a service
console.error("error catched", error);
return Observable.of({description: "Error Value Emitted"});
})
.subscribe(
val => console.log('Value emitted successfully', val),
error => {
console.error("This line is never called ",error);
},
() => console.log("HTTP Observable completed...")
);
}
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor}
from "@angular/common/http";
import {HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(req: HttpRequest<any>,
next: HttpHandler):Observable<HttpEvent<any>> {
const clonedRequest = req.clone({
headers: req.headers.set(
'X-CustomAuthHeader',
authService.getToken())
});
console.log("new headers", clonedRequest.headers.keys());
return next.handle(clonedRequest);
}
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
[ { provide: HTTP_INTERCEPTORS, useClass:
AuthInterceptor, multi: true } ]
],
bootstrap: [AppComponent]
})
export class AppModule {
}
longRequest() {
const request = new HttpRequest(
"POST", "/api/test-request", {},
{reportProgress: true});
this.http.request(request)
.subscribe(
event => {
if (event.type === HttpEventType.DownloadProgress) {
console.log("Download progress event", event);
}
if (event.type === HttpEventType.UploadProgress) {
console.log("Upload progress event", event);
}
if (event.type === HttpEventType.Response) {
console.log("response received...", event.body);
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment