[英]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.