【问题标题】:Spartacus - accessing user object from PDP page of Spartacus?Spartacus - 从 Spartacus 的 PDP 页面访问用户对象?
【发布时间】:2022-04-13 16:01:06
【问题描述】:

我是 SPA 新手,我正在尝试扩展 PDP 以通过单击按钮将某些数据发送到外部 API。

我已经能够在app.component.ts 中使用@spartacus/storefront 中的ProductDetailsOutlets 检索产品对象

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;
}

app.component.html 看起来像这样。

<cx-storefront></cx-storefront>

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

这里的问题是有没有一种方法可以在 Spartacus 中使用上述方法访问/检索当前登录的用户对象以及如何?

提前致谢!

【问题讨论】:

    标签: angular spartacus-storefront


    【解决方案1】:

    在 Spartacus 3.4 中访问已登录用户数据的最佳方法是使用 UserAccountFacade 中的 get() 方法。

    在您的app-wishlist-button 组件中,您可以添加以下代码:

    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) {}
    }
    

    您将获得一个包含用户数据的 Observable。然后,您可以在 Typescript 文件中订阅它:

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

    或在您的 html 中使用它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多