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