Angular 5+:子对象组件可观察到的父对象未隐藏时未获得值

问题描述 投票:2回答:1

EDIT 2This似乎是我的一般问题和解决方案(使用setTimeout可以发生Angular的生命周期)。如果可以,我将关闭此窗口或发布对自己问题的答案。

请参阅EDIT,它不涉及主题/可观察对象,但是本质上是相同的问题。”>

我有一个父组件,负责从服务中获取数据。

export class ParentComponent implements OnInit {
  public mySubject: Subject<Foo[]> = new Subject<Foo[]>();
  public buttonClicked = false;
  private currentValues: Foo[] = null;

  constructor(private SomeService myService) { }

  this.myService.get().subscribe(values => {
    this.mySubject.next(values); // Does NOT work when a child component is hidden, as expected.
    this.currentValues = values; // Keep value so we can manually fire later.
  });

  private buttonClickHandler() {
    this.buttonClicked = true;
    this.mySubject.next(this.currentValues);
  }
}

此数据由子组件在HTML中订阅。此组件通过*ngIf默认隐藏

,仅在单击按钮时可见:

<app-child-component [values]="mySubject.asObservable()" *ngif="buttonClicked" />

在上面的父组件中,您看到通过某种方式使该组件可见时,我正在尝试通过调用next()将当前可用数据传递给子组件:

this.mySubject.next(this.currentValues);

最初通过*ngIf取消隐藏组件时不起作用。如果我再次单击该按钮,然后再次调用next(),则它会按预期工作。但是,当Angular在取消隐藏某些内容的当前上下文中时,可观察对象不会获取其数据。 (当通过其他方法取消隐藏事物时也会发生这种情况,但结果是相同的:如果在同一方法中,则主题/数据传递不起作用;该组件在方法调用时必须已经可见。)

我猜想在方法调用解决后,直到*ngIf显示子组件之后,才会绑定到可观察对象。有什么地方可以吸引我的,然后我就可以向下传递子数据了吗?

为澄清请编辑

:我不认为这是SubjectBehaviorSubject的问题。我没有传递数据的问题。问题在于,数据传递(通过console.log()确认)根本没有发生。并非子组件正在接收null值。订阅只是不向孩子触发。

[我发现我也可以以更简单的方式重现此内容:如果我在同一Angular方法中将*ngIf的值设为true,则尝试选择*ngIf HTML的DOM中的元素会显示未定义。

<div *ngIf="buttonClicked">
  <div id="someElement">Foo</div>
</div>
public someMethod(): void {
  this.buttonClicked = true;
  const container = document.getElementById('someElement'); // DOES NOT WORK if this.buttonClicked was false at the start of this method!
}

编辑2:这似乎是我的一般问题和解决方案(使用setTimeout可以发生Angular的生命周期)。我将关闭此窗口,或者在可能时发布对自己问题的答案。请参阅编辑...

javascript angular event-handling observable lifecycle
1个回答
0
投票

您将需要使用BehaviourSubject而不是Subject,它最初会发出先前设置的值。

What is the difference between Subject and BehaviorSubject?

© www.soinside.com 2019 - 2024. All rights reserved.