问题
app.component.html
I have two components 1) ResetPassword 2) LoginComponent on the same router-outlet.
on successfully resetting the password. I'm redirecting to login component. How do I pass data from ResetPassword to LoginComponent?
I tried using subscribe method to do this but that is not working.
Can someone help me fix this.
LoginService
export class LoginService{
private messageSource = new BehaviorSubject('');
currentMessage = this.messageSource.asObservable();
setResetPassword(message: string) {
this.messageSource.next(message)
}
}
LoginComponent
OnInit{
this._loginService.currentMessage.subscribe(message => {
if (message !== undefined && message !== "") {
this.toastr.info(message);
}
});
}
ResetComponent
OnInit(){
this._loginService.setResetPassword("Password Changed Successfully");
}
回答1:
To pass data between component basically we use @Input
and @Output
, But in your case, I don't think this is the good approach.
So you can simply pass your message
as query params string (If data is not confidential) from reset password to Login component and then display as per requirements.
回答2:
Try with below code in LoginService.
import { Injectable, EventEmitter} from "@angular/core";
@Injectable()
export class LoginService {
currentMessage = new EventEmitter();
setResetPassword(message: string) {
this.currentMessage.emit(message)
}
}
And move your ResetComponent code in submit function.
resetPassword() {
this._loginService.setResetPassword("Password Changed Successfully");
}
Thanks.
回答3:
Change onInit ot ngOnInit it working for me
For your reference check the following code
<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)
}
}
来源:https://stackoverflow.com/questions/51166353/how-to-pass-data-between-one-component-to-another-which-is-on-same-router-outlet