分享

SAP Spartacus 开源项目里 activeCartId$ 的实现

 汪子熙 2022-04-29 发布于上海

我们可以在

app.module.ts

里使用如下代码,获得当前 cart id:

export class AppModule {
  constructor(_cart: ActiveCartService){
    _cart.getActiveCartId().subscribe((data) =>
    console.log('Jerry: ', data));
    console.log(_cart);
  }
}

打印输出:

在执行 Angular 依赖注入框架时,首先依次执行 pipe 操作符里的 Operator 逻辑,比如

take(1)

:

take 只是简单的返回一个 function,该 function 的触发时机?

在 pipe 操作里被调用:

此时再次返回一个新的函数:

Observable 的 lift 操作:

关于 take(1) 的使用场合:

当开发人员只对 stream 的第一个发射值感兴趣时,可以使用 take。 比如我们想查看用户在进入页面时首先点击了什么,或者想订阅 click 事件并获取第一次点击。 另一个用例是当需要在特定时间点进行数据快照的采集,但不需要进一步排放时。 例如,用户令牌更新流,或基于 Angular 应用程序中的流的路由保护。

如果想根据某些逻辑或另一个 observable 获取可变数量的值,可以使用 takeUntil 或 takeWhile.

take 与 skip 相反,其中 take 将采用前 n 个发射,而 skip 将跳过前 n 个发射。

下列例子会输出 1:

// RxJS v6+
import { of } from 'rxjs';
import { take } from 'rxjs/operators';

//emit 1,2,3,4,5
const source = of(1, 2, 3, 4, 5);
//take the first emitted value then complete
const example = source.pipe(take(1));
//output: 1
const subscribe = example.subscribe(val => console.log(val));

下列代码会输出整数序列 0,1,2,3,4:

// RxJS v6+
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';

//emit value every 1s
const interval$ = interval(1000);
//take the first 5 emitted values
const example = interval$.pipe(take(5));
//output: 0,1,2,3,4
const subscribe = example.subscribe(val => console.log(val));

下列代码会将第一次点击

div

标签的鼠标坐标,显示在 HTML 页面上:

// RxJS v6+
import { fromEvent } from 'rxjs';
import { take, tap } from 'rxjs/operators';

const oneClickEvent = fromEvent(document, 'click').pipe(
  take(1),
  tap(v => {
    document.getElementById(
      'locationDisplay'
    ).innerHTML = `Your first click was on location ${v.screenX}:${v.screenY}`;
  })
);

const subscribe = oneClickEvent.subscribe();

div 元素:

<div id="locationDisplay">
  Where would you click first?
</div>

pipe 函数里传入的所有操作,都记录在变量

fns

里了:

最后

activeCartId$

存放的就是 pipe 调用的返回结果:

开始执行

subscribe

了:

还得把

withLatestFrom

map

distinctUntilChanged

都依次执行一遍:

从调试上下文能够明显看出,先执行的 filter 里的匿名函数,再执行的 map 里的匿名函数:

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章