如何在同一路由器出口上的一个组件与另一个组件之间传递数据

时间:2018-07-04 05:30:04

标签: angular angular5

app.component.html

我有两个组成部分 1)ResetPassword 2)LoginComponent 在同一路由器出口上。

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

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

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

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");

}

3 个答案:

答案 0 :(得分:1)

基本上,我们要使用@Input@Output在组件之间传递数据,但是对于您而言,我认为这不是好方法。

因此,您只需将message作为查询参数字符串(如果数据为非机密)从重置密码传递到登录组件,然后按照要求。

答案 1 :(得分:1)

LoginService中尝试以下代码。

import { Injectable, EventEmitter} from "@angular/core";

@Injectable()
export class LoginService {

   currentMessage = new EventEmitter();

   setResetPassword(message: string) {
      this.currentMessage.emit(message)
   } 
}

并在提交功能中移动 ResetComponent 代码。

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

谢谢。

答案 2 :(得分:0)

更改onInit或ngOnInit对我有用

供参考,请检查以下代码

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