更新时间:2022-09-09 17:40:08
使用如下的代码监控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 =
filter(this.jerrytest2);
product$: Observable = 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 =
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,就不往下继续执行了: