如何在同一个路由器插座上将一个组件之间的数据传递到另一个组件



app.component.html

我有两个组件 1( 重置密码 2( 登录组件 在同一个路由器插座上。

成功重置密码时。我正在重定向到登录组件。 如何将数据从重置密码传递到登录组件?

我尝试使用订阅方法来执行此操作,但这不起作用。

有人可以帮我解决这个问题吗?

登录服务

export class LoginService{
private messageSource = new BehaviorSubject('');
currentMessage = this.messageSource.asObservable();
setResetPassword(message: string) {
this.messageSource.next(message)
} 
}

登录组件

OnInit{
this._loginService.currentMessage.subscribe(message => {
if (message !== undefined && message !== "") {
this.toastr.info(message);
}
});
}

重置组件

OnInit(){
this._loginService.setResetPassword("Password Changed Successfully");
}

为了在组件之间传递数据,基本上我们使用@Input@Output,但在你的情况下,我认为这不是好方法。

因此,您只需将message作为查询参数字符串(如果数据不机密(从重置密码传递到登录管理器组件,然后根据需要显示。

LoginService中尝试使用以下代码。

import { Injectable, EventEmitter} from "@angular/core";
@Injectable()
export class LoginService {
currentMessage = new EventEmitter();
setResetPassword(message: string) {
this.currentMessage.emit(message)
} 
}

并在提交函数中移动您的重置组件代码。

resetPassword() {
this._loginService.setResetPassword("Password Changed Successfully");
}

谢谢。

Change onInit ot ngOnInit for me

供您参考,请检查以下代码

<div><a></a></div>
<div><b></b></div>
@Component({
selector: 'b',
template: `<input [(ngModel)]="data" /> 
<button (click)="update()">update</button> `,
})
export class B implements OnInit {
data
constructor(public loginService: LoginService) {
}
ngOnInit() {
}
update() {
this.loginService.update(this.data)
}
}
@Component({
selector: 'a',
template: `<h1> {{data}}</h1> `,
})
export class A implements OnInit {
data
constructor(public loginService: LoginService) {
}
ngOnInit() {
this.loginService.currentMessage.subscribe((data) => {
this.data = data;
})
}
}
@Injectable({
providedIn: "root"
})
export class LoginService {
private messageSource = new BehaviorSubject('');
currentMessage = this.messageSource.asObservable();
update(message: string) {
this.messageSource.next(message)
}
}

最新更新