Search code examples
angularrxjsangular7url-routingangular-universal

need help on angular 7 Observable async pipe


Im trying to achieve page source wait from API call

    public responseTop: Observable<any>;
    this.responseTop = this.productSRV.topEquipments();
    this.responseTop.toPromise().then(sucess => {
        this.topEquipments = sucess['data'];
        // console.log('eq');
        // console.log(this.topEquipments);
        this.newsletterForm.controls.recaptchaReactive.setValue(sucess['message']);
      }).catch(error => {
        console.log('Error!', error);
    });

  <ng-container *ngFor="let topEq of topEquipments;">

as API is calling two times and how to put | async to wait for page source for SEO If i put

  <ng-container *ngIf="responseTop | async">

still it will not load in page source


Solution

  • once you call .then you execute it first time, when you use async it executes it second time.

    The question is - what is desired behavior?

    I would advise to combine them together:

    public responseTop: Observable<any>;
    this.responseTop = this.productSRV.topEquipments().pipe(
      // side effect
      tap(success => this.newsletterForm.controls.recaptchaReactive.setValue(success['message'])),   
    
      // mapping result to the array we need
      tap(console.log),
      map(success => success['data']),
    
      // catching error
      catchError(error => {
        console.log('Error!', error);
        throw error;
      }),
    );
    
    <ng-container *ngIf="responseTop | async as topEquipments">
      <ng-container *ngFor="let topEq of topEquipments">
        {{ topEq | json }}
      </ng-container> 
    </ng-container>