代码之家  ›  专栏  ›  技术社区  ›  Sergey Sokolov

zone.js/dist/zone-patch-rxjs的用途

  •  9
  • Sergey Sokolov  · 技术社区  · 8 年前

    也许我提这个问题来不及了,但无论如何。

    有人能解释一下在什么情况下我需要导入Zone的补丁吗- zone.js/dist/zone-patch-rxjs . 据我所知,这个补丁增加了 PR (继承人 this one )

    我用 zone RxJs 在我的 Angular 尽管看到了 make rxjs run in correct zone 在PR的描述中,我不完全理解什么时候它能帮助我或者它应该解决什么问题。

    我希望能有一些像before/after这样的代码示例。

    提前谢谢。

    1 回复  |  直到 8 年前
        1
  •  10
  •   jiali passion    8 年前

    你可以在这里查一下, https://github.com/angular/zone.js/blob/master/NON-STANDARD-APIS.md

    我们的想法是 rxjs 在不同的情况下进入正确的区域。

    js还提供了一个rxjs补丁,以确保rxjs observate/subscription/operator在正确的区域中运行。有关详细信息,请参阅请求843。下面的示例代码描述了这个想法。

    const constructorZone = Zone.current.fork({name: 'constructor'});
    const subscriptionZone = Zone.current.fork({name: 'subscription'});
    const operatorZone = Zone.current.fork({name: 'operator'});
    
    let observable;
    let subscriber;
    constructorZone.run(() => {
      observable = new Observable((_subscriber) => {
        subscriber = _subscriber;
        console.log('current zone when construct observable:', 
          Zone.current.name); // will output constructor.
        return () => {
          console.log('current zone when unsubscribe observable:', 
          Zone.current.name); // will output constructor.
        }
      });
    }); 
    
    subscriptionZone.run(() => {
      observable.subscribe(() => {
        console.log('current zone when subscription next', 
          Zone.current.name); // will output subscription. 
      }, () => {
        console.log('current zone when subscription error', d 
          Zone.current.name); // will output subscription. 
      }, () => {
        console.log('current zone when subscription complete', 
          Zone.current.name); // will output subscription. 
      });
    });
    
    operatorZone.run(() => {
      observable.map(() => {
        console.log('current zone when map operator', Zone.current.name); 
        // will output operator. 
      });
    });
    

    目前RXJSAPI基本上包括了

    • 可观察的
    • 订阅
    • 用户
    • 算子
    • 调度程序

    已修补,因此每个异步调用都将在正确的区域中运行。

    回答你的评论问题。

    不,这是不对的。 目前,如果没有补丁,每个回调都将运行在角度区域的内部或外部,这取决于发射器。这与何时创建回调无关。

    例如。

    let sub;
    ngZone.runOutsideAngular(() => {
       const observable = new Observable(subscriber => sub = subscriber));
       observable.subscribe(() => {
          // in ngzone
       });
    });
    
    ngZone.run(() => {
      sub.next(1);
    });
    

    在这种情况下,可观察到的是在角区域之外创建的,但是订阅服务器.NEXT被称为内角区域,所以最后,回调仍然在角区域。

    有了补丁,回调将在ngzone之外,因为它是在ngzone之外创建的。