angular observable code example
Example 1: understanding Observable.create(
import { Observable } from "rxjs/Observable";
var observable = Observable.create(function subscribe(observer) {
observer.next('Hey guys!')
})
var observable = Observable.create((observer:any) => {
observer.next('Hey guys!')
})
Example 2: observable tutorial angular
content_copy
const locations = new Observable((observer) => {
let watchId: number;
if ('geolocation' in navigator) {
watchId = navigator.geolocation.watchPosition((position: Position) => {
observer.next(position);
}, (error: PositionError) => {
observer.error(error);
});
} else {
observer.error('Geolocation not available');
}
return {
unsubscribe() {
navigator.geolocation.clearWatch(watchId);
}
};
});
const locationsSubscription = locations.subscribe({
next(position) {
console.log('Current Position: ', position);
},
error(msg) {
console.log('Error Getting Location: ', msg);
}
});
setTimeout(() => {
locationsSubscription.unsubscribe();
}, 10000);
Example 3: angular observable pipe exemple
import { Component, OnInit } from '@angular/core';
import { Observable, of} from 'rxjs';
import { map, filter, tap } from 'rxjs/operators'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
obs = new Observable((observer) => {
observer.next(1)
observer.next(2)
observer.next(3)
observer.next(4)
observer.next(5)
observer.complete()
}).pipe(
filter(data => data > 2),
map((val) => {return val as number * 2}),
)
data = [];
ngOnInit() {
this.obs1.subscribe(
val => {
console.log(this.data)
}
)
}
}