typescript observable code example
Example 1: promise to observable typescript
import { from } from 'rxjs';
const observable = from(promise);
Example 2: emit new value observable
const observable = new BehaviorSubject("initial value");
observable.subscribe({
next: (value) => console.log("The value is: ", value)
});
observable.next("a new value");
Example 3: 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);