// short form
providers: [PizzaService]
// long form
[{ provide: PizzaService, useClass: PizzaService }]
// with an object (good for Tests ;-))
let myService = {
getPizze: () => { return []; }
};
[{ provide: PizzaService, useValue: myService }]
Component({
selector: 'pizza'
})
export class PizzaComponent {
// use constructor to inject services
constructor(private pizzaService: PizzaService) {
}
}
fetchCustomerById(id, showCustomerFunc) {
openConnection(function(conn, err) {
if(err) {
// log
} else {
getCollec(conn, 'customers', function(col, err) {
if(err) {
// log
} else {
find(col, {'id': id}, function(result, err) {
showCustomerFunc(result);
})
}
})
}
})
}
fetchCustomerById(id, callback) {
return openConnection()
.then(conn => getCollection(conn, 'customers'))
.then(col => find(col, id))
.then(callback)
.catch(err => {
console.err(err);
throw err;
});
}
supplyAsync(this::api)
.thenApply(this::api2)
.thenAccept(this::handleResult);
import {Observable} from "rxjs";
const source = Observable.of(1, 2, 3);
source.subscribe(x => console.log(x));
// 1
// 2
// 3
Observable.of(1, 2, 3)
.map(n => n * n)
.filter(n => n >= 4)
.subscribe(x => console.log(x));
// 4
// 9
const src: Observable<number> = Observable.of(1, 2, 3);
const sub: Subscription = src
.subscribe(x => console.log(x));
sub.unsubscribe();
const src: Observable<number> = fetchNumbers();
// ... nothing happens ;-)
src.subscribe(nr => console.log(nr));
// now the request is sent
searchControl
// if a value changes
.valueChanges
// wait for 500ms after the last change
.debounceTime(500)
// only if the new value differs
.distinctUntilChanged()
// only the last known value
// unsubscribe from old values
.switchMap(search => this.dataService.find(search))
// give me data!
.subscribe(items => this.items = items);
function in service that executes the GET call
import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
import {Pizza} from "./pizza.model";
@Injectable()
export class PizzaService {
constructor(private http: HttpClient) { }
gimmePizza(): Observable<Pizza[]> {
return this.http.get<Pizza[]>('api/pizze');
}
}
call the service in the component and subscribe to the Observable.
export class PizzeComponent implements OnInit {
pizze: Pizza[];
constructor(private pizzaService: PizzaService) {
}
ngOnInit() {
this.pizzaService.gimmePizza()
.subscribe(pizze => this.pizze = pizze);
}
}
movies: Movie[];
moviesSubscription: Subscription;
constructor(private movieService: MovieService) {
}
ngOnInit() {
this.moviesSubscription = this.movieService
.getAllMovies()
.subscribe(movies => this.movies = movies);
}
ngOnDestroy() {
this.moviesSubscription.unsubscribe();
}
movies: Observable<Movie[]>;
constructor(private movieService: MovieService) {
}
ngOnInit(): void {
this.movies = this.movieService.getAllMovies();
}
<movie *ngFor="let movie of movies | async"
[movie]="movie"
(removeMovie)="onRemoveMovie($event)">
</movie>