how to pass data between one component to another which is on same router-outlet

你。 提交于 2019-12-25 02:18:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!