Search code examples
angularsap-commerce-cloudspartacus-storefront

Retrieve current B2B Unit for Customer in Spartacus


I want to show current B2B Unit name in the header. What would be the correct way to retrieve B2B Unit for current customer?

What I found so far, there is a payload for /current? endpoint which is loaded on initial page load and it contains the orgUnit:

Payload for /current?

When I was trying to retrieve the Unit via CurrentUnitService, I got null value.

unit.component.ts:

orgUnit$: Observable<B2BUnit> = this.currentUnitService.item$;

  constructor(
    protected currentUnitService: CurrentUnitService,
  ) {}

unit.component.html:

  <ng-container *ngIf="orgUnit$ | async as unit">
    <p class="d-inline-block">{{unit.name}}&nbsp;</p>
    <a href="#" class="d-inline-block">
      ({{unit.uid}})
    </a>
  </ng-container>

Solution

  • I was able to retrieve the B2BUnit for current customer using UserAccountFacade and by extending User model with orgUnit as follows:

    unit.component.ts

    export class UnitComponent implements OnInit {
      user$: Observable<CustomUser | undefined>;
    
      constructor(
        protected auth: AuthService,
        protected userAccount: UserAccountFacade
      ) {}
    
      ngOnInit(): void {
        this.user$ = this.auth.isUserLoggedIn().pipe(
          switchMap(isUserLoggedIn => {
            if (isUserLoggedIn) {
              return this.userAccount.get();
            } else {
              return of(undefined);
            }
          })
        );
      }
    }
    
    interface CustomUser extends User {
      orgUnit?: B2BUnit
    }
    

    unit.component.html

    <ng-container *ngIf="user$ | async as user">
        <p class="d-inline-block">{{user.orgUnit?.name}}&nbsp;</p>
        <a href="#" class="d-inline-block">
          ({{user.orgUnit?.uid}})
        </a>
        <p>{{ user.name }}</p>
      </ng-container>
    

    Result:

    enter image description here