首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >链接可观察结果

链接可观察结果
EN

Stack Overflow用户
提问于 2022-06-26 10:09:49
回答 1查看 84关注 0票数 0

我正在尝试从角类“customerID”中获取UserFacade,然后使用检索到的customerID,使用http调用REST端点来检索客户端点。

我使用的方法是创建两个变量--用户$和点$,必须正确初始化它们,这将保证正确地接收到这些点。是否有更好的方法来实现这个逻辑,例如,不使用这两个变量--用户$和点$--并通过函数getPts():number直接检索它们

HTML:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<div class="box">
  <ng-container *ngIf="user$ | async as user">
    <ng-container *ngIf="point$ | async as point">
         <p>  {{getCustomerPoints()}}  </p> 
    </ng-container>
  </ng-container>

</div>

这就是主要逻辑所在:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { Component, OnInit } from '@angular/core';
import { AuthService, CmsComponent, User, UserIdService, } from '@spartacus/core';
import { CmsComponentData } from '@spartacus/storefront';
import { UserAccountFacade } from '@spartacus/user/account/root';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { switchMap } from 'rxjs/operators';
import { PointsRetrievalService } from '../points-retrieval.service';
import { FOOTER_VALUE, HEADER_VALUE } from './component-labels';


export interface CustomerPoints {
  points: number;
}


export interface CmsSlpCustomUserPointsComponent4 extends CmsComponent {
  title: string;
  headerText: string;
  footerText: string;
}

@Component({
  selector: 'app-userpoints',
  templateUrl: './userpoints.component.html',
  styleUrls: ['./userpoints.component.scss']
})
export class UserpointsComponent implements OnInit {
  public point$!: Observable<CustomerPoints>;
  user$: Observable<User | undefined> | undefined;
  data$: Observable<CmsSlpCustomUserPointsComponent4> = this.component.data$;
  private customerPointsRetrieved = 0
  constructor(
    public component: CmsComponentData<CmsSlpCustomUserPointsComponent4>, private pointsRetrievalService: PointsRetrievalService,
    protected auth: AuthService,
    protected userAccount: UserAccountFacade,
    protected userIdService: UserIdService,
  ) {}


  ngOnInit() : void {
    this.user$ = this.auth.isUserLoggedIn().pipe(
      switchMap(isUserLoggedIn => {
        if (isUserLoggedIn) {
     
          this.userAccount.get().subscribe(
            (user) =>
            {
              if(user && user?.customerId)
              {
                this.point$ = this.pointsRetrievalService.getPointsForCustomerId(user?.customerId) 
                this.point$.subscribe(
                  (userPoints) =>
                  {
                    console.log("New points:" +userPoints.points)
                    console.log(userPoints.points)
                    this.customerPointsRetrieved = userPoints.points
                  }
                )
              }
            }
          )
      
          return this.userAccount.get();  
        } else {
          return of(undefined);
        }
      })
    );

  }



getCustomerPoints()
{
  return this.customerPointsRetrieved;
}

}

通过http检索点的服务:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserAccountFacade } from '@spartacus/user/account/root';
import { BASE_SITE_ID, CUSTOMER_ID, ELECTRONICS_SITE, HTTP_JSON_HEADERS, REST_URL } from './userpoints/rest-connection-constants';
import { CustomerPoints } from './userpoints/customer-points-interfaces';
@Injectable({
  providedIn: 'root'
})

export class PointsRetrievalService{

  constructor(private http: HttpClient,
    protected userAccount: UserAccountFacade) {

  }

  getPointsForCustomerId(userID: string): Observable<CustomerPoints>
   {
    {
      console.log("User id received:" + userID)
      const url = `${REST_URL}${userID}`;
      //const url = this.mainRestUrl + this.userIdUsed + this.fieldParams;
      console.log(url);

      let params = new HttpParams().set(CUSTOMER_ID, userID).set(BASE_SITE_ID, ELECTRONICS_SITE);

      const options = { params: params, headers: HTTP_JSON_HEADERS }

      return this.http.get<CustomerPoints>(url, options);
    }

  }


}
EN

回答 1

Stack Overflow用户

发布于 2022-06-26 11:26:29

我不认为user$point$流有什么意义。

而且,ngOnInit中的逻辑看起来有点复杂(通常嵌套订阅不是一个好模式)。

我做了一些改变,但我真的不能测试任何东西,所以如果你有问题,请告诉我。也许你可以让它适应工作。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import {
    Observable,
    of,
    Subject,
} from 'rxjs';
import {
    switchMap,
    takeUntil,
    tap,
} from 'rxjs/operators';

import {
    Component,
    OnDestroy,
    OnInit,
} from '@angular/core';
import {
    AuthService,
    CmsComponent,
    UserIdService,
} from '@spartacus/core';
import { CmsComponentData } from '@spartacus/storefront';
import { UserAccountFacade } from '@spartacus/user/account/root';

import { PointsRetrievalService } from '../points-retrieval.service';

export interface CustomerPoints {
    points: number;
}


export interface CmsSlpCustomUserPointsComponent4 extends CmsComponent {
    title: string;
    headerText: string;
    footerText: string;
}

const customerPointsKey = 'CUSTOMER_POINTS_KEY';

@Component({
    selector: 'app-userpoints',
    templateUrl: './userpoints.component.html',
    styleUrls: ['./userpoints.component.scss']
})
export class UserpointsComponent implements OnInit, OnDestroy {
    data$: Observable<CmsSlpCustomUserPointsComponent4> = this.component.data$;
    private customerPointsRetrieved = localStorage.getItem(customerPointsKey) ?? 0;
    private _destroyed$ = new Subject<void>();
    constructor(
        public component: CmsComponentData<CmsSlpCustomUserPointsComponent4>, private pointsRetrievalService: PointsRetrievalService,
        protected auth: AuthService,
        protected userAccount: UserAccountFacade,
        protected userIdService: UserIdService,
    ) { }

    ngOnInit(): void {
        this.auth.isUserLoggedIn().pipe(
            switchMap(isUserLoggedIn => {
                if (isUserLoggedIn) {
                    return this.userAccount.get().pipe(
                        switchMap(user => {
                            if (user && user?.customerId) {
                                return this.pointsRetrievalService.getPointsForCustomerId(user.customerId).pipe(
                                    tap(userPoints => {
                                        console.log("New points:" userPoints.points)
                                        console.log(userPoints.points)
                                        this.customerPointsRetrieved = userPoints.points;
                                        localStorage.setItem(customerPointsKey, userPoints.points);
                                    })
                                )
                            }

                            return of(undefined);
                        })
                    )
                }

                return of(undefined);
            }),
            takeUntil(this._destroyed$),
        ).subscribe();
    }

    ngOnDestroy(): void {
        this._destroyed$.next();
    }

    getCustomerPoints() {
        return this.customerPointsRetrieved;
    }

}
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<div class="box">
  <p>{{getCustomerPoints()}}</p> 
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72764076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文