前端analysis | What,Why,Who,When,Where,How

《angular8》- Rxjs 深入了解走向高端

2020-06-13

下面进入总结主题:

Observable是什么?

  • 通俗解释,形如发布订阅模式
  • 目的在于解耦代码,便于angular业务逻辑之间异步传递值,此时类似promise
  • 简单例子
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
     const locations = new Observable((observer) => {
    let watchId: number;

    // Simple geolocation API check provides values to publish
    if ('geolocation' in navigator) {
    watchId = navigator.geolocation.watchPosition((position: Position) => {
    observer.next(position);
    }, (error: PositionError) => {
    observer.error(error);
    });
    } else {
    observer.error('Geolocation not available');
    }

    // When the consumer unsubscribes, clean up data ready for next subscription.
    return {
    unsubscribe() {
    navigator.geolocation.clearWatch(watchId);
    }
    };
    });

    // Call subscribe() to start listening for updates.
    const locationsSubscription = locations.subscribe({
    next(position) {
    console.log('Current Position: ', position);
    },
    error(msg) {
    console.log('Error Getting Location: ', msg);
    }
    });

    // Stop listening for location after 10 seconds
    setTimeout(() => {
    locationsSubscription.unsubscribe();
    }, 10000);

Rxjs 核心概念

Observable

operators

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏