SAP Spartacus CurrentProductService返回的null对象

时间:2022-07-25
本文章向大家介绍SAP Spartacus CurrentProductService返回的null对象,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用如下的代码监控getProduct可能返回的null值:

import { Component, OnInit } from '@angular/core';
import { ActiveCartService, Product } from '@spartacus/core';
import { CurrentProductService } from '@spartacus/storefront';
import { Observable, OperatorFunction } from 'rxjs';
import { filter, map } from 'rxjs/operators';

@Component({
  selector: 'app-mycom',
  templateUrl: './mycom.component.html',
  styleUrls: ['./mycom.component.scss']
})
export class MycomComponent implements OnInit {

  jerryfilter: OperatorFunction<Product, Product> =
    filter(this.jerrytest2);

  product$: Observable<Product> = this.currentProductService.getProduct().pipe(this.jerryfilter);

  productName$ = this.product$.pipe(map(product => product.name));

  jerrytest2(product: Product): boolean {
    const result = !!product;
    if (result === false) {
      console.log('false!');
    }
    return result;
  }

  constructor(private currentProductService: CurrentProductService, private cartService: ActiveCartService
  ) {
  }

  ngOnInit(): void {
    this.product$.subscribe(product => console.log(product));
  }

}

TypeScript语句jerryfilter: OperatorFunction<Product, Product> = filter(this.jerrytest2);

对应的JavaScript函数:

jerryfilter的JavaScript实现是一个名字叫filter的function,接收一个predicate function作为输入参数,返回一个新的函数,总金额和新的函数会基于传进来的predicate新建一个filterOperator实例:

export function filter(predicate, thisArg) {
    return function filterOperatorFunction(source) {
        return source.lift(new FilterOperator(predicate, thisArg));
    };

product$: Observable = this.currentProductService.getProduct().pipe(this.jerryfilter);

注意,product$是一个Observable对象,不是实际的product值:

operator指向了我传入的filter.

product$也是Observable,因此可以继续调用pipe.

返回为false的情况:

filter的实现,如果箭头函数返回false,就不往下继续执行了: