簡體   English   中英

Angular 子組件在父 oninit 期間父函數未初始化

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

我在ResetPasswordComponent oninit 中觸發時顯示警報時出現問題。 AlertService的訂閱塊沒有被觸發,但是如果我將代碼從 oninit 移動到構造函數,它將起作用。 但是,將初始化/聲明代碼放在構造函數中似乎不是一個好習慣。 那么有沒有更好的解決方案呢?

家長

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");
    }
  }
}

孩子

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();
  }
}

警報服務

@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();

}

我認為問題在於該事件是在子組件開始訂閱 ngOnInit 之前觸發的。 當子組件最終訂閱時,“無效鏈接”事件已經發生並結束。

對此有幾種解決方案,一種是將您的主題更改為 BehaviorSubject,例如:

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

現在,只要孩子訂閱了,它就會從 Observable 接收最后一個事件,即使在事件發生之后也是如此。

另一種解決方案可能是將 shareReplay() 運算符添加到您的 observable 中。 但是在這種特定情況下,當您已經在使用主題時,我會使用 BehaviorSubject 解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM