Angular 5
(and new magic)
Hello World size: 210kb
(60kb polyfills)
non gzipped
HttpModule
from'@angular/http'
- @deprecated and will be removed in angular 6 (~May 2018)
- size ~15kb
New features
- size ~20kb
- Allow Angular Universal(SSR)
- JSON is now the default response
- Interceptors (aka middleware)
- Listening to progress events
- Security: XSRF Protection
HttpClientModule from'@angular/common/http'
JSON is now the default response.
export class ApiService {
fancyMethod() {
return this.http.get('url')
.map(res => res.json());
}
}Previously
export class ApiService {
fancyMethod() {
return this.http.get('url');
}
}Now
this.http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
// Here, resp is of type HttpResponse<MyJsonData>.
// You can inspect its headers:
console.log(resp.headers.get('X-Custom-Header'));
// And access the body directly
console.log(resp.body.someField);
});If you want raw response:
Interceptors
@Injectable()
export class JWTInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
authorization: localStorage.getItem('token')
}
});
return next.handle(req);
}
}Add header to every request
@Injectable()
class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).catch(err => {
if (err instanceof HttpErrorResponse {
if (err.status === 401) {
// JWT expired, go to login
}
}
});
}
}or http error handling
and logging, caching requests, ...
Service Worker
$ npm install @angular/service-worker
(https required)
Features / Use Cases
- Reliability - Provide static, dynamic and external resources from cache
- Performance - Only reach out to network if necessary
- Push Notifications - Sending push messages to users for re-engagement
Enabling SW Support
// .angular-cli.json
{
...
"apps": [
{
...
"serviceWorker": "true"
}
]
}<!doctype html>
<html>
...
<body>
<aio-shell></aio-shell>
<script src="polyfills.{HASH}.bundle.js"></script>
<script src="sw-register.{HASH}.bundle.js"></script>
<script src="main.{HASH}.bundle.js"></script>
</body>
</html>Angular CLI will now add a Service Worker registration script to our production build
Behind the scenes:
- Adds script for Service Worker registration to index.html
- Copies Service Worker bundle to dist/
- Generates a ngsw-manifest.json
External Content Cache
// ngsw-manifest.json
{
...
"external": {
"urls": [
{ "url": "https://fonts.googleapis.com/css?family=..." },
{ "url": "https://fonts.gstatic.com/s/materialicons/..." }
]
}
}There are much more awesome features, but i'm too lazy to finish...
Angular 5
By lynxeyedua
Angular 5
- 17