-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs-ts-ng.html
More file actions
876 lines (762 loc) · 28.7 KB
/
js-ts-ng.html
File metadata and controls
876 lines (762 loc) · 28.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
<title>TS Doc</title>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<style>
pre.prettyprint {
padding-top: 7.5px;
border-radius: 5px;
border: .5px solid rgb(220, 220, 220);
font-size: .8em;
white-space: pre-wrap;
background-color: #f6f8fa;
}
mark {
font-size: 13px;
font-family: 'Courier New', Courier, monospace;
}
html {
scroll-behavior: smooth;
}
</style>
</head>
<body>
<div class="container mt-5">
<section id="sass">
<h2 class="text-info">Sass / CSS</h2>
<div class="row">
<div class="col-12">
<Label>Media Query breakpoints</Label>
<pre class="prettyprint">
/* General Styles here */
/* Layouts that apply for smallest screens @media (min-width: 0) { ... } here */
@media (min-width: 576px) {}
@media (min-width: 768px) {}
@media (min-width: 992px) {}
@media (min-width: 1200px) {}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label>CSS Grid</Label>
<pre class="prettyprint">
<style>
.wrapper {
display: grid;
/* Gap between rows and cols */
gap: 1em;
/* Partition of every row */
grid-template-columns: 1fr 1fr;
/* different syntax
grid-template-columns: repeat(2, 1fr) */
/* Fixed height of all Rows*/
grid-auto-rows: 5em;
/* Min height of row with auto scaling */
grid-auto-rows: minmax(5em, auto);
}
.wrapper>div.box-c{
/* Place box-c in the second row (it already this, this is redundant here) */
grid-row: 2;
/* Use columns from 1 until 3.
This div will now span across 2 columns
That's the entire length of the wrapper container
because row was partitioned into two cols with (1fr 1fr) */
grid-column: 1 - 3;
/*Bezieht sich auf das element in einer Reihe. Nicht die Reihe selbst*/
justify-self: end;
}
</style>
<body>
<div class="container">
<div class="wrapper">
<div></div>
<div></div>
<div class="box-c"></div>
</div>
</div>
</body>
</html>
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><code>sass input.scss output.css</code></Label><br>
<Label><code>sass .\style.scss style.css --no-source-map --watch --style compressed</code></Label><br>
<Label><code>sass ./:./someDirectory --no-source-maps</code></Label>
<pre class="prettyprint">
//_colors.scss
$primary-color: rgb(201, 201, 201);
// main.scss
@import './colors';
body {
color: $primary-color;
}
</pre>
</div>
</div>
</section>
<section id="node">
<h2 class="text-success">Node.js</h2>
<code>express my-app</code>
<br>
<code>"start": "node -r esm .\\app.js"</code>
<div class="row">
<div class="col-12">
<Label>API</Label>
<pre class="prettyprint lang-javascript">
const express = require('express');
const app = express()
.use(express.urlencoded())
.use(express.json())
.use(cors);
const port = 3000;
// localhost:3000
// localhost:3000/
app.get('', (req, res) => {
res.send({ some: 'json' });
// res.send('<p>some html<p>');
// res.status(404).send('Sorry, cant find that');
// error
res.send('something else');
res.end();
});
// localhost:3000/students/31?use=1
app.get('/students/:id', (req, res) => {
// req.params.id
// req.query.use
res.end();
});
app.post('/', (req, res) => {
// request.body is the post body as js object.
// request.body.name ...
res.end();
});
// localhost:3000/dassakdapsdaks
app.get('**', (req, res) => {
res.status(404);
res.end();
});
app.listen(port, 'localhost', () => console.log('Listening on Port ' + port));
function cors(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
};
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label>Serve Angular App</Label>
<pre class="prettyprint lang-javascript">
// Build Angular app with: ng b
// Put /dist folder into this directory
const express = require('express');
const path = require('path');
const app = new express();
const port = 3000;
app.use(express.static(__dirname + '/dist'));
app.get('*', function (_req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
app.listen(port, () => console.log(`Server listening on ${port}`));
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<b>
<Label>Mongodb</Label><br></b>
<Label>MongoDb im atlas: clusterpassword im query string ist nicht der mongodb account name</Label>
<Label>Um direkt auf Windows mit DB zu arbeiten: Shell runterladen, mongoinstallpath/bin zu Path Variable hinzufügen</Label>
<Label>mongo "mongodb+srv://cluster0-7yq8x.mongodb.net/test" --username dyrestium</Label>
<pre class="prettyprint lang-javascript">
// const MongoClient = require('mongodb').MongoClient;
import { MongoClient } from 'mongodb';
const uri = 'mongodb+srv://dyrestium:?@cluster0-7yq8x.mongodb.net/test?retryWrites=true&w=majority';
MongoClient.connect(uri, (err, db) => {
if (err) throw err;
const dbo = db.db('bankingApp');
dbo.collection('users').updateOne({ firstName: /Oscar/ }, { $set: { firstName: 'Updated' } });
dbo.collection('users')
.find({ firstName: /Osc/g })
.toArray()
.then((res) => {
console.log(res);
});
db.close();
});
</pre>
</div>
</div>
</section>
<hr role="separator">
<section id="typescript">
<h2 class="text-info">Typescript</h2>
<div class="row">
<div class="col-12">
<Label>Hash</Label><br>
<code>npm i js-sha256</code>
<pre class="prettyprint lang-javascript">
import { sha256 } from "js-sha256";
// ca66a852a9e96c40f4cce7972d994914909b646b2564e8d25dd4003656b3dd63
let x = sha256('Oscar');
// Node..
const sha256 = require("js-sha256");
var x = sha256('Oscar');
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label>Get Date 1</Label>
<pre class="prettyprint lang-javascript">
// 12.1.2020 13:30:7
function parseDate(d: Date, addTime: boolean = true): string {
return `${d.getDate()}.${(d.getMonth() + 1)}.${d.getFullYear()}`
+ (addTime ? ` ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}` : '');
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label>Get Date 2</Label>
<pre class="prettyprint lang-javascript">
// 12.01.2020 13:30:07
function parseDate(d: Date, addTime: boolean = true): string {
return addPadding( `${d.getDate()}.${(d.getMonth() + 1)}.${d.getFullYear()}`
+ (addTime ? ` ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}` : ''), addTime);
}
function addPadding(s: string, addTime: boolean = true): string {
if (s[2] != '.') {
s = insertAt(s, '0', 0);
}
if (s[5] != '.') {
s = insertAt(s, '0', 3);
}
if (addTime) {
if (s[13] != ':') {
s = insertAt(s, '0', 11);
}
if (s[16] != ':') {
s = insertAt(s, '0', 14);
}
if (s.length < 19) {
s = insertAt(s, '0', 17);
}
}
return s;
}
function insertAt(s: string, stringToInsert: string, index: number): string{
return s.substr(0, index) + stringToInsert + s.substr(index);
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<label>InsertAtIndex</label>
<pre class="prettyprint lang-typescript">
function insertAt(index: any, arr: any[], ...toInsert: any[]) {
const left = arr.slice(0, index);
const right = arr.slice(index);
return left.concat(toInsert)
.concat(right);
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<label>Get age</label>
<pre class="prettyprint lang-typescript">
function getAge(date: Date): number {
const now = new Date();
const dateYears = date.getFullYear();
const nowYears = now.getFullYear();
if (now.getMonth() > date.getMonth()) {
return nowYears - dateYears;
} else if (now.getMonth() < date.getMonth()) {
return nowYears - dateYears - 1;
} else if (now.getDate() > date.getDate() - 1) {
return nowYears - dateYears;
} else {
return nowYears - dateYears - 1;
}
}
</pre>
</div>
</div>
<section id="types">
<h4>Types</h4>
<div class="row">
<div class="col-12">
<pre class="prettyprint lang-typescript">
// Check primitive types with typeof
const d = 31;
typeof d == "number"; // True
typeof d == "string"; // False
typeof d == "Student"; // Compile Error
// ---------------------------------------
// Check instance types with instanceof
class Student { }
class Kid extends Student { }
const s = new Student();
s instanceof Student; // True;
const k = new Kid();
k instanceof Kid; // True;
k instanceof Student; // True;
</pre>
</div>
</div>
</section>
<section id="async">
<h4>Async, Await, Promise, ...</h4>
<div class="row">
<div class="col-12">
<pre class="prettyprint lang-typescript">
// The Promise gets executed right away.
new Promise<string | number>((resolve, reject) => {
// Make API Call
// ...
// On Success
resolve('...');
// On Fail
reject(404);
}).then(data => {
// data is typeof string | number
console.log(data + ' resolved');
}).catch(data => {
// data is typeof string | number
console.log(data + ' rejected');
});
</pre>
</div>
</div>
</section>
</section>
<hr role="separator">
<section id="angular">
<h2 class="text-primary">Angular</h2>
<section id="cli">
<h4>CLI Commands</h4>
<div class="row">
<div class="col-12">
<pre class="prettyprint lang-typescript">
ng new my-sassy-app --style=scss
// Github Pages
ng build --output-path docs --prod --base-href https://kexplx.github.io/tictac/
// Use sass in existing App
ng config schematics.@schematics/angular:component.styleext scss
</pre>
</div>
</div>
</section>
<section id="services">
<h4>Services</h4>
<div class="row">
<div class="col-12">
<p><code>ng g s log --spec false</code></p>
<Label><small>Define service - <i>log.service.ts</i></small></Label>
<pre class="prettyprint lang-typescript">
import { Injectable } from '@angular/core';
// @Injectable does two things here
// 1. providedIn: 'root' puts the service in the highest level.
// which makes this services accesible by any component
//
// 2. @Injectable() makes this service able to be injected with another service
// @Component is therefor by default Injectable
@Injectable({
providedIn: 'root'
})
export class LogService {
// ...
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Inject service, provided in root.</small></Label>
<pre class="prettyprint lang-typescript">
import { LogService } from './services/log.service';
@Component({
// ...
})
export class UseComponent {
// This logService is provided in root
// It's shared between all components
constructor(private logService: LogService) {}
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Inject service, created for this component.</small></Label>
<pre class="prettyprint lang-typescript">
import { LogService } from './services/log.service';
// Here, instead of using the LogService instance that is provided in root.
// We demand our own instance by specifiying it in the providers array.
@Component({
// ...
providers: [
LogService
]
})
export class UseComponent {
// new LogService()
constructor(private logService: LogService) {}
}
</pre>
</div>
</div>
</section>
<hr role="separator">
<section id="routing">
<h4>Routing</h4>
<div class="row">
<div class="col-12">
<Label><small>Define routes in <i>app-routing.module.ts</i> use in
<i>app.module.ts</i></small></Label>
<pre class="prettyprint lang-typescript">
const appRoutes: Routes = [
{path: 'students', component: StudentListComponent, children: [
{path: ':id', component: StudentDetailComponent}
]},
{path: '', redirectTo: 'students', pathMatch: 'full'},
{path: '**', component: NotFoundComponent}
];
@NgModule({
declarations: [],
imports: [
CommonModule,
<mark>RouterModule.forRoot(appRoutes)</mark>
],
exports: [
<mark>RouterModule</mark>
]
})
export class AppRoutingModule { }
// .................................................................
@NgModule({
declarations: [
AppComponent,
StudentDetailComponent,
StudentListComponent,
NotFoundComponent,
],
imports: [
FormsModule,
BrowserModule,
<mark>AppRoutingModule</mark>
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Render Route based components into template -
<i>app.component.html</i></small></Label>
<pre class="prettyprint lang-html">
<!-- On Load with right URL components will be rendered into <router-outlet></router-outlet> -->
<router-outlet></router-outlet>
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Use ng-properties instead of <code>href</code></small></Label>
<pre class="prettyprint lang-html">
<!-- Click will go to /students/{id}?showId=0 -->
<!-- when having '/' infront it uses the absolute path -->
<button [routerLink] = "['/students', student.id]" [queryParams]="{showId:'0'}"></button>
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Access route and query params programmaticly. All the query params
will be strings initially (Careful when looking for id:number === queryParam:string)
</small></Label>
<pre class="prettyprint lang-typescript">
import { ActivatedRoute } from '@angular/router';
// .................................................
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// this.route.snapshot only is the current form of the url
// when the url changes e.g. a new id is entered
// the component will not do anything e.g. update the id
// Access .../{id} and parse the string.
const id: number = Number(this.route.snapshot.params.id);
// Access .../...?showId query param and parse to boolean.
const param = this.route.snapshot.queryParams.showId === '1' ? true : false;
// If the Route below the current parent changes, while we are in that parent
// students/1 -> students/2
// The url has to be subscribed to to get notify of that change
this.route.params.subscribe((params: Params) => {
this.id = params.id;
}
);
this.route.queryParams.subscribe((queryParams: Params) => {
this.queryParam = queryParams.use;
});
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Navigate programmaticly</small></Label>
<pre class="prettyprint lang-typescript">
import { ActivatedRoute, Router } from '@angular/router';
// .................................................
constructor(private route: ActivatedRoute, private route: Router) { }
navigateAbsolute() {
// servers/edit?myParam=ay#lmao
this.router.navigate(['/servers', 'edit'],
{queryParams: {myParam: 'ay'}, fragment: 'lmao'});
}
navigateRelative() {
// .../edit?paramOfCurrentRoute=1
this.router.navigate(['edit'],
{relativeTo: this-route, queryParamsHandling: 'preserve'});
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Can Activate Guards</small></Label>
<pre class="prettyprint lang-typescript">
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean> | Promise<boolean> | boolean {
return new Promise<boolean>((resolve, reject) => {
// Make API call
// Call resolve(), reject()
}).then((result) => {
// Route is allowed.
return true;
}).catch((result) => {
// Route is not allowed, redirect accordingly.
this.router.navigate(['/not-allowed']);
return false;
});
}
}
// ................................................
const appRoutes: Routes = [
{path: 'students', component: StudentListComponent, children: [
{path: ':id', component: StudentDetailComponent, <mark>canActivate: [AuthGuardService]}</mark>
]},
{path: 'not-allowed', component: NotAllowedComponent},
{path: '', redirectTo: 'students', pathMatch: 'full'},
{path: '**', component: NotFoundComponent}
];
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Can Deactivate Guards. The interface and the service are boilerplate.
</small></Label>
<pre class="prettyprint lang-typescript">
import { Observable } from 'rxjs';
export interface CanDeactivateComponent {
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean;
}
// ..........................................
import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { CanDeactivateComponent } from './canDeactivateComponent';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CanDeactivateGuardService implements CanDeactivate<CanDeactivateComponent> {
canDeactivate(component: CanDeactivateComponent,
currentRoute: ActivatedRouteSnapshot,
currentSate: RouterStateSnapshot,
nextState?: RouterStateSnapshot):
Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate();
}
constructor() { }
}
// .........................................
export class MyComponent CanDeactivateComponent {
// ....
canDeactivate(): boolean | Promise<boolean> | Observable<boolean> {
// Check if Route should be left.
// return true;
// return false;
// return confirm('Do you want to discard the changes?');
}
}
// .........................................
const appRoutes: Routes = [
{path: 'students', component: StudentListComponent, <mark>canDeactivate: [CanDeactivateGuardService]</mark>, children: [
{path: ':id', component: StudentDetailComponent, canActivate: [AuthGuardService]}
]},
{path: 'not-allowed', component: NotAllowedComponent},
{path: '', redirectTo: 'students', pathMatch: 'full'},
{path: '**', component: NotFoundComponent}
];
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Pass static data to component on route load.</small></Label>
<pre class="prettyprint lang-typescript">
{path: 'some-route', component: MyComponent, data: {myMessage: 'Page not found'}},
// .....
// In the component ...
ngOnInit() {
this.errorMessageToBind = this.route.snapshot.data.myMessage;
}
</pre>
</div>
</div>
<div class="row">
<div class="col-12">
<Label><small>Use Resolver to preload data before the component is rendered. <br>
This is an alternative to fetching that data in the onInit() method of said component.
<br>
When using a resolver, the component often no longer needs a service to get the data
from.
The Resolver will throw the data into the route.data object.
</small></Label>
<pre class="prettyprint lang-typescript">
@Injectable({
providedIn: 'root'
})
export class StudentResolverService implements Resolve<Student> {
constructor(public studentService: StudentService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<Student> | Promise<Student> | Student {
return this.studentService.getStudentById(+route.params.id);
}
}
// .................................
@Component({
selector: 'app-student-detail',
templateUrl: './student-detail.component.html',
styleUrls: ['./student-detail.component.css']
})
export class StudentDetailComponent implements OnInit {
student: Student;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.data.subscribe(
(data: Data) => {
this.student = data.student;
}
);
}
}
// .................................
{path: ':id', component: StudentDetailComponent, <mark>resolve: {student: StudentResolverService}</mark>, canActivate: [AuthGuardService]}
</pre>
</div>
</div>
</section>
<section>
<h4>HTTP</h4>
<div class="row">
<div class="col-12">
<pre class="prettyprint lang-typescript">
// HTTP Service...
constructor(private http: HttpClient) { }
let queryParams = new HttpParams();
queryParams = queryParams.append('param1', 'value1');
queryParams = queryParams.append('param2', 'value2');
return this.http.get<Student[]>('http://localhost:3001',
{
observe: 'body', // Get entire response with 'response',
headers: new HttpHeaders({'MyHeader': 'Hello'}, {'abcd': 'ab'}),
params: queryParams,
responseType: 'json' // default
})
// Pipe function only runs when no error (Server returns 4** code).
.pipe(map(responseData => {
const result: Student[] = [];
// ...
return result;
}), catchError(errorRes => {
// Send to analytics...
// Yields the error to the subscribe below...
return throwError(errorRes);
}), tap(event => {
if(event.type === HttpEventType.Response) {
// Response was received
// event.body can be accessed
}
if(event.type === HttpEventType.Sent) {
// Request was sent
}
});
// Components
service.makeGet(). // gets the observable
subscribe((responseData: Student[]) => {
// ...
}, error => {
// error.status -> 404
// error.statusText -> Not Found
// error.error -> response.send('My Node Message')
});
// ..............................................
import {HttpInterceptor, HttpRequest} form '@angular/common/http'
// Runs code right before a http request leaves the app
export class AuthInterCeptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedRequest = req.clone({headers: req.headers.append('myheader': 'value')});
next.handle(modifiedRequest).pipe(tap(event => {
if(event.type === HttpEventType.Response) {
// Response arrived
// event.body
}
}));
}
}
@NgModel({
// ...
providers:
[
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterCeptorService,
multi: true
}
]
}
</pre>
</div>
</div>
</section>
</section>
</div>
</body>
</html>