简体   繁体   English

Angular - 为什么每次发出新值时都会调用 ngOnInit?

[英]Angular - Why ngOnInit is called every time i emit a new value?

I have a Subject called refreshSubject$ inside my service.我的服务中有一个名为refreshSubject$的主题。

  private refreshUsers$ = new Subject<User[]>();

He is emitting a new value every time the user is added.每次添加用户时,他都会发出一个新值。

  saveUser(user: User[]) {
    return this.http.post<User>(this.url, user)
      .pipe(
        tap(() => {
          this.refreshUsers$.next();
        })
      );
  }

Im using a get method on my service to retrieve the value我在我的服务上使用 get 方法来检索值

  get refresh$() {
    return this.refreshUsers$;
  }

Now every time i add a new user, i emit a new value using the next() method.现在每次我添加一个新用户时,我都会使用next()方法发出一个新值。

  this.refreshUsers$.next();

Inside my component i have my life cycle hook ngOnInit that he is being called everytime the refreshUsers$ subject emits a new value.在我的组件中,我有我的生命周期钩子 ngOnInit,每次refreshUsers$主题发出新值时都会调用它。

  ngOnInit(): void {
    this.apiService.refresh$.subscribe(() => {
      this.getAllUsers();
    });
  }

Why ngOnInit is called every time i subscribe to a new value ?为什么每次订阅新值时都会调用 ngOnInit ?

In the onInit you are subscribed to your subject so everytime you emit a new value the method "this.getAllUsers()" will be runned.在 onInit 中,您订阅了您的主题,因此每次发出新值时,都会运行方法“this.getAllUsers()”。 It doesn't matter if you are subscribed in the OnInit.您是否订阅了 OnInit 并不重要。 A subscribe is alive until you unsubscribe.订阅一直有效,直到您取消订阅。

Subscribe will get trigger every time an event is emitted does not matter where it sits.订阅将在每次发出事件时触发,无论它位于何处。 So your ngOnIt is not getting trigger every time an event is triggered but it's "subscribe", but since your's subscribe is inside "ngOnInIt" it will look like "ngOnInIt" is getting triggered.因此,您的 ngOnIt不会在每次触发事件时触发,而是“订阅”,但由于您的订阅在“ngOnInIt”内,因此看起来像是“ngOnInIt”被触发。 If you don't want this you can move out your subscribe outside ngOnInIt although it will not create a problem.如果你不想要这个,你可以将你的订阅移出 ngOnInIt 之外,尽管它不会产生问题。 Because other logic you have written inside ngOnInIt will not get triggered.因为您在 ngOnInIt 中编写的其他逻辑不会被触发。

If you want to check for yourself you can add a console.log("testing") inside your ngOnInit but outside of subscribe.如果您想自己检查,您可以在 ngOnInit 中但在订阅之外添加一个 console.log("testing") 。 And emmit multiple event our will notice that 'testing' will be logged only once(when component loads)并发出多个事件,我们会注意到“测试”只会记录一次(当组件加载时)

It's not... the subscription callback is called everytime you emit a value, ie, this part:这不是......每次发出值时都会调用订阅回调,即这部分:

() => {
      this.getAllUsers();
}

But you are not making a new subscription every time you emit a value.但是您并不是在每次发出值时都进行新的订阅。

That's how observables work这就是 observables 的工作原理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM