Context
Recently, I wanted to use observable in one of my ionic 4 project, client wanted to show a progress bar during the file uploading process, So that i decided to use it and googled for the example, but unfortunately i did’t find any best Typescript observable example that fulfill my needs and i spent so much time to make it work as i expected, that why i’m writing this post to share a sample code for the same.
Code Samples
testObservable() {
var i = 0;
return new Observable<Upload>((observer) => {
var int = setInterval(()=>{
i++;
var data = {
status: 'In progress',
url: 'bbbb',
percent: ( i / 10 )
};
console.log(i);
console.log((i==10));
if(i>9){
clearInterval(int);
data.status= 'Completed';
observer.next(data);
observer.complete();
}
observer.next(data);
console.log(data);
},1500);
});
}
class Upload {
public status: string;
public url: string;
public percent: number;
}
this.obsData$ = this.testObservable();
this.obsData$.subscribe(
(responseObj: any) => { // On next
console.log(responseObj);
},
(error:any) => console.log(error),
() => { // On complete
}
)
HTML page
<p>{{ ( obsData$ | async )?.status}}</p>
<ion-progress-bar value="{{( obsData$ | async )?.percent }}"></ion-progress-bar>
You may contact me if you need any further help
Sijo Vijayan