首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Zone.js/dist/zone的用途-修补程序-rxjs

Zone.js/dist/zone的用途-修补程序-rxjs
EN

Stack Overflow用户
提问于 2018-06-10 14:36:03
回答 1查看 3.5K关注 0票数 13

也许我提这个问题太迟了,但无论如何。

有人能解释一下在什么情况下我需要导入区域的补丁- zone.js/dist/zone-patch-rxjs。据我所知,这个补丁是在这个按下 (这一个的继承者)中添加的。

我在我的zone项目中使用了RxJsAngular,尽管在PR的描述中看到了make rxjs run in correct zone,但我并不完全理解它什么时候可以帮助我,或者它应该为我解决什么问题。

我希望有一些代码示例,如“前”/“后”。

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-10 15:31:33

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

这样做的目的是让rxjs在不同的情况下进入正确的区域。

zone.js还提供了一个rxjs修补程序,以确保rxjs可观察/订阅/操作符在正确的区域中运行。详情请参阅拉动请求843。下面的示例代码描述了这个想法。

代码语言:javascript
复制
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. 
  });
});

目前,rxjs包括的内容基本上都包括

  • 可观察
  • 订阅
  • 订阅者
  • 运算符
  • 调度器

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

回答你的评论问题。

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

例如。

代码语言:javascript
复制
let sub;
ngZone.runOutsideAngular(() => {
   const observable = new Observable(subscriber => sub = subscriber));
   observable.subscribe(() => {
      // in ngzone
   });
});

ngZone.run(() => {
  sub.next(1);
});

在这种情况下,可观测到的是在角区域之外创建的,但是subscriber.next在角区域内被调用,所以最后,回调仍然在角区域。

使用该修补程序,回调将位于ngzone的外部,因为它是在ngzone之外创建的。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50784775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档