Skip to content

Commit 15c195f

Browse files
committed
first commit with httpclient example
1 parent 79d2529 commit 15c195f

File tree

8 files changed

+329
-25
lines changed

8 files changed

+329
-25
lines changed

src/app/app.component.html

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,7 @@
11
<!--The content below is only a placeholder and can be replaced.-->
22
<div style="text-align:center">
3-
<h1>
3+
<p>
44
Welcome to {{title}}!
5-
</h1>
6-
<img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=">
5+
</p>
76
</div>
8-
<h2>Here are some links to help you start: </h2>
9-
<ul>
10-
<li>
11-
<h2><a target="_blank" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
12-
</li>
13-
<li>
14-
<h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
15-
</li>
16-
<li>
17-
<h2><a target="_blank" href="http://angularjs.blogspot.com/">Angular blog</a></h2>
18-
</li>
19-
</ul>
207

src/app/app.component.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,27 @@
1-
import { Component } from '@angular/core';
1+
import {Component, OnInit} from '@angular/core';
2+
import {HttpclientService} from "./services/httpclient.service";
23

34
@Component({
45
selector: 'app-root',
56
templateUrl: './app.component.html',
67
styleUrls: ['./app.component.css']
78
})
8-
export class AppComponent {
9-
title = 'app';
9+
export class AppComponent implements OnInit{
10+
11+
title: string;
12+
13+
constructor(private httpClient: HttpclientService) {
14+
15+
}
16+
17+
ngOnInit(): void {
18+
this.httpClient.getUserData().subscribe(
19+
data => {
20+
console.log(JSON.stringify(data));
21+
this.title = JSON.stringify(data);
22+
}
23+
);
24+
}
25+
26+
1027
}

src/app/app.module.ts

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,25 @@
1-
import { BrowserModule } from '@angular/platform-browser';
2-
import { NgModule } from '@angular/core';
3-
4-
import { AppComponent } from './app.component';
1+
import {BrowserModule} from "@angular/platform-browser";
2+
import {NgModule} from "@angular/core";
3+
import {AppComponent} from "./app.component";
4+
import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http";
5+
import {HttpclientService} from "./services/httpclient.service";
6+
import {AuthInterceptor} from "./intercepter/auth-interceptor";
7+
import {AuthService} from "./services/auth.service";
58

69
@NgModule({
710
declarations: [
811
AppComponent
912
],
1013
imports: [
11-
BrowserModule
14+
BrowserModule,
15+
HttpClientModule
16+
],
17+
providers: [
18+
HttpclientService,
19+
AuthService,
20+
{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}
1221
],
13-
providers: [],
1422
bootstrap: [AppComponent]
1523
})
16-
export class AppModule { }
24+
export class AppModule {
25+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import {Injectable} from "@angular/core";
2+
import {HttpEvent, HttpHandler, HttpInterceptor}
3+
from "@angular/common/http";
4+
import {HttpRequest} from "@angular/common/http";
5+
import {Observable} from "rxjs/Observable";
6+
import {AuthService} from "../services/auth.service";
7+
8+
@Injectable()
9+
export class AuthInterceptor implements HttpInterceptor {
10+
11+
constructor(private authService: AuthService) {
12+
}
13+
14+
intercept(req: HttpRequest<any>,
15+
next: HttpHandler):Observable<HttpEvent<any>> {
16+
17+
/*const clonedRequest = req.clone({
18+
headers: req.headers.set('X-CustomAuthHeader', authService.getToken())
19+
});
20+
console.log("new headers", clonedRequest.headers.keys());*/
21+
console.log(req);
22+
return next.handle(req);
23+
}
24+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { TestBed, inject } from '@angular/core/testing';
2+
3+
import { AuthService } from './auth.service';
4+
5+
describe('AuthService', () => {
6+
beforeEach(() => {
7+
TestBed.configureTestingModule({
8+
providers: [AuthService]
9+
});
10+
});
11+
12+
it('should be created', inject([AuthService], (service: AuthService) => {
13+
expect(service).toBeTruthy();
14+
}));
15+
});

src/app/services/auth.service.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { Injectable } from '@angular/core';
2+
3+
@Injectable()
4+
export class AuthService {
5+
6+
constructor() { }
7+
8+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { TestBed, inject } from '@angular/core/testing';
2+
3+
import { HttpclientService } from './httpclient.service';
4+
5+
describe('HttpclientService', () => {
6+
beforeEach(() => {
7+
TestBed.configureTestingModule({
8+
providers: [HttpclientService]
9+
});
10+
});
11+
12+
it('should be created', inject([HttpclientService], (service: HttpclientService) => {
13+
expect(service).toBeTruthy();
14+
}));
15+
});
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
import { Injectable } from '@angular/core';
2+
import {HttpClient, HttpEventType, HttpHeaders, HttpRequest} from "@angular/common/http";
3+
import {Observable} from "rxjs/Observable";
4+
import "rxjs/add/operator/catch";
5+
import "rxjs/add/observable/of";
6+
import "rxjs/add/operator/switchMap";
7+
import "rxjs/add/observable/forkJoin";
8+
import "rxjs/add/operator/map";
9+
import "rxjs/add/operator/shareReplay";
10+
11+
@Injectable()
12+
export class HttpclientService {
13+
14+
courses$: Observable<Course[]>;
15+
16+
constructor(private http: HttpClient) { }
17+
18+
getUserData() {
19+
return this.http.get('https://api.github.com/users/seeschweiler');
20+
}
21+
22+
longRequest() {
23+
24+
const request = new HttpRequest(
25+
"POST", "/api/test-request", {},
26+
{reportProgress: true});
27+
28+
this.http.request(request)
29+
.subscribe(
30+
event => {
31+
32+
if (event.type === HttpEventType.DownloadProgress) {
33+
console.log("Download progress event", event);
34+
}
35+
36+
if (event.type === HttpEventType.UploadProgress) {
37+
console.log("Upload progress event", event);
38+
}
39+
40+
if (event.type === HttpEventType.Response) {
41+
console.log("response received...", event.body);
42+
}
43+
44+
}
45+
);
46+
}
47+
48+
throwError() {
49+
50+
this.http
51+
.get("/api/simulate-error")
52+
.catch( error => {
53+
// here we can show an error message to the user,
54+
// for example via a service
55+
console.error("error catched", error);
56+
57+
return Observable.of({description: "Error Value Emitted"});
58+
})
59+
.subscribe(
60+
val => console.log('Value emitted successfully', val),
61+
error => {
62+
console.error("This line is never called ",error);
63+
},
64+
() => console.log("HTTP Observable completed...")
65+
);
66+
}
67+
68+
sequentialRequests() {
69+
70+
const sequence$ = this.http.get<Course>(
71+
'/courses/-KgVwEBq5wbFnjj7O8Fp.json')
72+
.switchMap(course => {
73+
course.description+= ' - TEST ';
74+
return this.http.put('/courses/-KgVwEBq5wbFnjj7O8Fp.json', course)
75+
},
76+
(firstHTTPResult, secondHTTPResult) =>
77+
[firstHTTPResult, secondHTTPResult]);
78+
79+
sequence$.subscribe(
80+
values => console.log("result observable ", values)
81+
);
82+
83+
}
84+
85+
sequentialRequests1() {
86+
87+
const sequence$ = this.http.get<Course>(
88+
'/courses/-KgVwEBq5wbFnjj7O8Fp.json')
89+
.switchMap(course => {
90+
91+
course.description+= ' - TEST ';
92+
93+
return this.http.put(
94+
'/courses/-KgVwEBq5wbFnjj7O8Fp.json',
95+
course)
96+
});
97+
sequence$.subscribe();
98+
99+
}
100+
101+
parallelRequests() {
102+
103+
const parallel$ = Observable.forkJoin(
104+
this.http.get('/courses/-KgVwEBq5wbFnjj7O8Fp.json'),
105+
this.http.get('/courses/-KgVwECOnlc-LHb_B0cQ.json')
106+
);
107+
108+
parallel$.subscribe(
109+
values => {
110+
console.log("all values", values)
111+
}
112+
);
113+
}
114+
115+
shareReply() {
116+
const httpGet$ = this.http
117+
.get("/courses.json")
118+
.map(data => data)
119+
.shareReplay();
120+
}
121+
122+
duplicateRequestsExample() {
123+
124+
const httpGet$ = this.http
125+
.get("/courses.json")
126+
.map(data => data);
127+
128+
httpGet$.subscribe(
129+
(val) => console.log("logging GET value", val)
130+
);
131+
132+
this.courses$ = httpGet$;
133+
}
134+
135+
httpPostExample() {
136+
137+
this.http.post("/courses/-KgVwECOnlc-LHb_B0cQ.json",
138+
{
139+
"courseListIcon": "...",
140+
"description": "TEST",
141+
"iconUrl": "..",
142+
"longDescription": "...",
143+
"url": "new-url"
144+
})
145+
.subscribe(
146+
(val) => {
147+
console.log("POST call successful value returned in body",
148+
val);
149+
},
150+
response => {
151+
console.log("POST call in error", response);
152+
},
153+
() => {
154+
console.log("The POST observable is now completed.");
155+
});
156+
}
157+
158+
httpDeleteExample() {
159+
160+
this.http.delete("/courses/-KgVwECOnlc-LHb_B0cQ.json")
161+
.subscribe(
162+
(val) => {
163+
console.log("DELETE call successful value returned in body",
164+
val);
165+
},
166+
response => {
167+
console.log("DELETE call in error", response);
168+
},
169+
() => {
170+
console.log("The DELETE observable is now completed.");
171+
});
172+
}
173+
174+
httpPatchExample() {
175+
176+
this.http.patch("/courses/-KgVwECOnlc-LHb_B0cQ.json",
177+
{
178+
"description": "Angular Tutorial For Beginners PATCH TEST",
179+
})
180+
.subscribe(
181+
(val) => {
182+
console.log("PATCH call successful value returned in body",
183+
val);
184+
},
185+
response => {
186+
console.log("PATCH call in error", response);
187+
},
188+
() => {
189+
console.log("The PATCH observable is now completed.");
190+
});
191+
}
192+
193+
httpPutExample() {
194+
195+
const headers = new HttpHeaders()
196+
.set("Content-Type", "application/json");
197+
198+
this.http.put("/courses/-KgVwECOnlc-LHb_B0cQ.json",
199+
{
200+
"courseListIcon": ".../main-page-logo-small-hat.png",
201+
"description": "Angular Tutorial For Beginners TEST",
202+
"iconUrl": ".../angular2-for-beginners.jpg",
203+
"longDescription": "...",
204+
"url": "new-value-for-url"
205+
},
206+
{headers})
207+
.subscribe(
208+
val => {
209+
console.log("PUT call successful value returned in body",
210+
val);
211+
},
212+
response => {
213+
console.log("PUT call in error", response);
214+
},
215+
() => {
216+
console.log("The PUT observable is now completed.");
217+
}
218+
);
219+
}
220+
221+
}
222+
223+
interface Course {
224+
description: string;
225+
courseListIcon:string;
226+
iconUrl:string;
227+
longDescription:string;
228+
url:string;
229+
}

0 commit comments

Comments
 (0)