22
loading...
This website collects cookies to deliver better user experience
import { from } from 'rxjs';
// Observable out of a promise
const records= from(fetch('/api/endpoint'));
// Subscribe to begin listening for async result
data.subscribe({
next(response) { console.log(response); },
error(err) { console.error('Error: ' + err); },
complete() { console.log('Completed'); }
});
import { interval } from 'rxjs';
// Create an Observable that will publish a value on an interval
const counter= interval(1000);
// Subscribe to begin publishing values
const subscription = counter.subscribe(n =>
console.log(`It's been ${n + 1} seconds since subscribing!`));
import { ajax } from 'rxjs/ajax';
// To create an AJAX request
const dataFromApi= ajax('/api/data');
// Subscribe to create the request
dataFromApi.subscribe(res => console.log(res.status, res.response));
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
const numbers= of(1, 2, 3);
const squareValuesofNumber = map((val: number) => val * val);
const squaredNums = squareValuesOfNumbers(numbers);
squaredNums.subscribe(x => console.log(x));
// Logs
// 1
// 4
// 9
import { of, pipe } from 'rxjs';
import { filter, map } from 'rxjs/operators';
const numbers = of(1, 2, 3, 4, 5);
// function that accepts an Observable.
const squareOfOddVals = pipe(
filter((n: number) => n % 2 !== 0),
map(n => n * n)
);
// Observable that will run the filter and map functions
const squareOfOdd = squareOfOddVals(numbers);
// Subscribe to run the combined functions
squareOfOdd.subscribe(x => console.log(x));
import { of } from 'rxjs';
import { filter, map } from 'rxjs/operators';
const squareOfOdd = of(1, 2, 3, 4, 5)
.pipe(
filter(n => n % 2 !== 0),
map(n => n * n)
);
// Subscribe to get values
squareOfOdd.subscribe(x => console.log(x));
import { of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, catchError } from 'rxjs/operators';
// Return "response" from the API. If an error happens,
// return an empty array.
const dataFromApi = ajax('/api/data').pipe(
map((res: any) => {
if (!res.response) {
throw new Error('Value expected!');
}
return res.response;
}),
catchError(err => of([]))
);
dataFromApi.subscribe({
next(x) { console.log('data: ', x); },
error(err) { console.log('errors already caught... will not run'); }
});