Http, Angular 2

in 10 minutes

Marcell Kiss

marcellkiss@budacode.com

Developer

Co-Organizer

Example

import {Http, HTTP_PROVIDERS} from 'angular2/http';

@Component({
  selector: 'http-app',
  viewProviders: [HTTP_PROVIDERS],
  templateUrl: 'people.html'
})

class PeopleComponent {
  constructor(http: Http) {
    http.get('people.json')
    // Call map on the response observable
    .map(res => res.json())
    // Subscribe to the observable
    .subscribe(people => this.people = people);
  }
}

Text

Http API

https://angular.io/docs/ts/latest/api/http/Http-class.html

constructor(
_backend: ConnectionBackend,       _defaultOptions: RequestOptions
)

request(
url: string | Request, 
options?: RequestOptionsArgs
) : Observable<Response>
get(
url: string, 
options?: RequestOptionsArgs
) : Observable<Response>

Classes

Request - method, headers, url

Response - type, ok, url, ..., json(), text()

RequestOptions

ResponseOptions

Headers

MockBackend

Change headers

let headers = new Headers();
headers.append('Content-Type', 'application/json');

let authToken = localStorage.getItem('auth_token');
headers.append('Authorization', `Bearer ${authToken}`);

return this.http
  .get('/profile', { headers: headers })

Observable benefits

RxJS 5 is everywhere
keywords: observer, observable, operator

Easy to cancel (dispose)

Complex compositions

Data streams

Observable operators

.map

// Using a function
var source = Rx.Observable.range(1, 3)
    .map(function (x, idx, obs) {
        return x * x;
    });

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// => Next: 1
// => Next: 4
// => Next: 9
// => Completed

Observables, more...

map

filter

delay

retry

forkJoin

flatMap

Good old modules

$resource -> no info

restangular 2 ->  WIP

Conclusion

Observables 

Documentation

Learning curve

Thanks

for your attention!

Q & A

@martzellk

Sources

Http in Angular 2

By Marcell Kiss

Http in Angular 2

  • 1,538