17 December 2020

RXJS Call api in nested http - Angular v2

 


(Mục đích của RXJS trong các ví dụ dưới đây là call api và tiền xử lý data cuối cùng trả giá trị về một lần duy nhất)

switchMap + forkJoin

Gọi api Child loop theo dữ liệu array của api Parent => return 1 object data
RXJS 2020
import { forkJoin } from 'rxjs';
import { switchMap } from 'rxjs/operators';
this.api.get('themes/my_themes').pipe( switchMap(s => forkJoin( s.docs.map(m => { return this.api.get('themes/' + m.themeId) }) )) ).subscribe(res => { this.myTemplates = res });

switchMap + of

Rxjs convert
RXJS 2020
import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

this.api.get('themes/my_themes')
  .pipe(switchMap(s => of(s.map(m => m.theme))))
  .subscribe(res => {
  this.myTemplates = res
});
Rxjs convert
2020
// Get themes and theme [Rxjs: Multi request]
    this.api.get('themes').pipe(switchMap(s => forkJoin(
        s.docs.map(t => this.api.get('websiteData/' + t.websiteDataId).pipe(switchMap(w => of ({
            themeName: t.themeName,
            themeId: t._id,
            configs: JSON.parse(w.themeConfig)
        }))))
    ))).subscribe((res: any) => {
        this.theme = res.find((el) => el.themeId == this.editorService.websiteData.themeId);
        this.themes = res;
        this.changeDetectorRef.detectChanges();
    });
Rxjs convert
2020
this.api.get('websiteData/' + this.params.id).pipe(
    switchMap(s => forkJoin(
        this.api.get('themes'),
        this.api.get('themes/' + s['themeId']),
    ))).pipe().subscribe(res => {
    console.log(res);
    this.themes = res[0].docs;
    this.theme = res[1];
});
Rxjs convert
2020
// Get themes and theme [Rxjs: Multi request]
this.api.get('themes').pipe(switchMap(s => forkJoin(s.docs.map(m => this.api.get('websiteData/' + m.websiteDataId).pipe(switchMap(t => of ({
        ...t,
        ...m,
        configs: JSON.parse(t.themeConfig)
    }))))))).subscribe((res: any) => {
        this.theme = res.find((el) => el.websiteDataId == this.pageCurrent.websiteDataId);
        this.themes = res;
    }
);
Rxjs convert
2020
// Rxjs: ForkJoin multi request http [Fix big issue]
const pageRes = await of(this.websiteData.pageDataIds).pipe(switchMap(s => forkJoin(s.map(m => this.api.get('pageData/' + m))))).toPromise();
Rxjs cho html2Canvas the/catch -> await async toPromise or subscribe
2020
import { from, Observable } from 'rxjs';
import html2canvas from "html2canvas";
public getImage(element): Observable <any> {
    const options = {
        useCORS: true,
        allowTaint: true,
        backgroundColor: null
    };
    return from(
        html2canvas(element, options).then(
            canv => {
                return canv.toDataURL('image/png');
            }, err => {
                throw new Error(err);
            }
        ).catch(res => {
            throw new Error(res);
        })
    );
}

...Còn update tiếp 

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang