简体   繁体   English

Angular 子组件在父 oninit 期间父函数未初始化

[英]Angular child component not initialised when parent is function during parent oninit

I having a problem showing my alert when triggered in ResetPasswordComponent oninit.我在ResetPasswordComponent oninit 中触发时显示警报时出现问题。 The subscribe block for AlertService is not being triggered however if I move the code from oninit to the constructor it will work. AlertService的订阅块没有被触发,但是如果我将代码从 oninit 移动到构造函数,它将起作用。 However it does not seem like it's a good practice to put initialization/declaration code in the constructor.但是,将初始化/声明代码放在构造函数中似乎不是一个好习惯。 So is there a better solution to this?那么有没有更好的解决方案呢?

Parent家长

export class ResetPasswordComponent implements OnInit {
  public email: string;
  public token: string;

  constructor(public alertService: AlertService) {
  }

  ngOnInit() {
    this.token = this.route.snapshot.queryParamMap.get('token');
    this.email = this.route.snapshot.queryParamMap.get('email');
    console.log("Parent on init");
    if (this.token === null || this.token === "" ||
        this.email === null || this.email === "") {
      this.form.disable();
      this.alertService.error("Invalid link");
    }
  }
}

Child孩子

export class AlertComponent implements OnInit, OnDestroy {
  private subscription: Subscription;
  public messages: string[];
  public type: string;

  constructor(private alertService: AlertService) {

  }

  ngOnInit() {
    console.log(this.alertService.getAlert());
    this.subscription = this.alertService.getAlert().subscribe(data => {
      console.log("OK");
      // do something
    });
    console.log("Child On init");
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

AlertService警报服务

@Injectable({ providedIn: 'root' })
export class AlertService {
  private subject = new Subject<Alert>();

  constructor(private router: Router) { }

  error(message: any, navigateTo = null) {
    if (navigateTo !== null) {
      this.navigateWithMessage(navigateTo, AlertType.error, message);
    }
    const alert: Alert = { type: AlertType.error, message };
    this.subject.next(alert);
    console.log("NEXT");
  }

  getAlert(): Observable<Alert> {
    return this.subject.asObservable();

}

I believe the problem is that the event is triggered before the child component has started subscribing in the ngOnInit.我认为问题在于该事件是在子组件开始订阅 ngOnInit 之前触发的。 When the child component finally subscribes, the "Invalid link" event has already happened and is finished.当子组件最终订阅时,“无效链接”事件已经发生并结束。

There is a couple of solutions to this, one is changing your Subject to a BehaviorSubject, like:对此有几种解决方案,一种是将您的主题更改为 BehaviorSubject,例如:

private subject = new BehaviorSubject<Alert>(null);

Now, as soon as the child subscribes, it will receive the last event from the Observable, even after the event has happened.现在,只要孩子订阅了,它就会从 Observable 接收最后一个事件,即使在事件发生之后也是如此。

Another solution could be adding the shareReplay() operator to your observable.另一种解决方案可能是将 shareReplay() 运算符添加到您的 observable 中。 But in this specific case, when you are already using subjects, I would go with the BehaviorSubject solution.但是在这种特定情况下,当您已经在使用主题时,我会使用 BehaviorSubject 解决方案。

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

相关问题 导航到子组件时父组件重新初始化 - Parent component getting re-initialised when navigating to child component 当有Parent Component和Child Component时,为什么在Parent OnInit之前调用Child Constructor? - When there is a Parent Component and a Child Component, why is the Child Constructor called before the Parent OnInit? Angular2:子组件如何在onInit之后持续侦听父组件的输入 - Angular2: How can a child component consistently listen to an input from the parent component after onInit 角2父级和子级分量 - angular 2 parent and child component 在Angular 2中将函数从Parent传递给Child组件 - Pass function from Parent to Child component in Angular 2 导航到第一个孩子时触发父路由 OnInit - Parent route OnInit triggers when navigating to first child 当子组件位于路由器出口Angular中时,从子组件调用父组件函数 - Call parent component function from child when child components are in router outlet Angular 来自父组件的子组件中的角度调用函数 - Angular calling function in child component from parent component Angular 10:从父组件调用子组件函数 - Angular 10: Call a child component function from parent component 从 angular 中的兄弟组件的子组件调用父组件 function - calling parent component function from child of siblings component in angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM