Skip to content

Instantly share code, notes, and snippets.

@ahmadarif
Last active January 22, 2019 12:42
Show Gist options
  • Save ahmadarif/8e3c1dd2a41fb9f838b46cb32587a9a6 to your computer and use it in GitHub Desktop.
Save ahmadarif/8e3c1dd2a41fb9f838b46cb32587a9a6 to your computer and use it in GitHub Desktop.
Implementasi observe events di Angular HttpClient

Implementasi 1

this.uploadService.create(GANTI_DENGAN_OBJECT_CLASS_UPLOAD).pipe(
  catchError((err: HttpErrorResponse) => {
    const res = err.error as Response<null>;
    console.log('Uploading error:', res.message);
    return Observable.throw(null);
  }))
  .subscribe((event: HttpEvent<any>) => {
    switch (event.type) {
      case HttpEventType.UploadProgress:
        if (event.total) {
          const percentage = Math.round((event.loaded / event.total) * 100);
          console.log(`${percentage}%`);
        }
        break;
      case HttpEventType.Response:
        const res = (event as HttpResponse<any>).body as Response<null>;
        console.log("success upload:", res.message);
        break;
    }
  });

Implementasi 2 (pakai Subject)

# deklarasi class variable
createSubject = new Subject<Upload>();

...

# deklarasi subject listener di ngOnInit
this.createSubject.pipe(switchMap((req: Upload) => {
  return this.uploadService.create(req).pipe(
    catchError((err: HttpErrorResponse) => {
      const res = err.error as Response<null>;
      console.log('Uploading error:', res.message);
      return Observable.throw(null);
    })
  )}), retry())
  .subscribe((event: HttpEvent<any>) => {
    switch (event.type) {
      case HttpEventType.UploadProgress:
        if (event.total) {
          const percentage = Math.round((event.loaded / event.total) * 100);
          console.log(`${percentage}%`)
        }
        break;
      case HttpEventType.Response:
        const res = (event as HttpResponse<any>).body as Response<null>;
        console.log("success upload:", res.message);
        break;
    }
  });

...

# panggil subject di fungsi start upload
upload(obj: Upload) {
  this.createSubject.next(obj);
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UploadService {
constructor(private http: HttpClient) { }
create (obj: Upload) {
const body = new FormData();
body.append('filename', obj.file.name);
if (obj.file) body.append('file', obj.file, obj.file.name);
return this.http.post('UPLOAD_ENDPOINT', body, { reportProgress: true, observe: 'events' });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment