Search code examples
angularspartacus-storefront

Spartacus - accessing user object from PDP page of Spartacus?


I am new to SPA and I am trying to extend the PDP to send certain data to an external API using a button click.

I have been able to retrieve the product object using the ProductDetailsOutlets from @spartacus/storefront in app.component.ts

import { Component } from '@angular/core';
import { ProductDetailOutlets } from '@spartacus/storefront';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'wishlistStore';

  pdpOutlets = ProductDetailOutlets;
}

The app.component.html looks like this.

<cx-storefront></cx-storefront>

<ng-template [cxOutletRef]="pdpOutlets.SUMMARY" let-product>
    <!-- {{ product | json }} -->
    <app-wishlist-button [productDetails]="product"></app-wishlist-button>
</ng-template>

Question here is there a way to access/retrieve the currently logged in user object using the above approach in Spartacus and how?

Thanks in advance!


Solution

  • The best way to access the logged in user data in in Spartacus 3.4 would be by using the get() method in the UserAccountFacade.

    In your app-wishlist-button component you can add the following code:

    import { Component } from '@angular/core';
    import { User } from '@spartacus/core';
    import { UserAccountFacade } from '@spartacus/user/account/root';
    import { Observable } from 'rxjs';
    
    @Component({
      selector: 'app-wishlist-button',
      templateUrl: 'wishlist-button.component.html',
    })
    export class WishlistButtonComponent {
      user$: Observable<User> = this.userAccountService.get();
    
      constructor(protected userAccountService: UserAccountFacade) {}
    }
    

    You will get an Observable with the user data. You can then either subscribe to it in your Typescript file:

    onClick() {
     this.user$.subscribe((user: User) => {
      // You can access user here
     });
    }
    

    or use it in your html:

    <ng-container *ngIf="user$ | async as user">
     <button (click)="onClick(user)">Do Action</button>
    </ng-container>