使用eventemitter将值传递给父组件

时间:2018-11-26 14:59:03

标签: angular angular-event-emitter

如何将模态组件中“ mytoki”的值发送给其父组件?

我不确定是否应该创建另一个EventEmitter或服务。有什么建议么 ?

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  @Output()
  toHide = new EventEmitter();

  private usrname;
  private pswd;
  private visible: string;
  private mytoki;

  constructor(private loginservice: LoginService) { }

  ngOnInit() {
  }

  connect(usrname, pswd) {
    this.loginservice.getUserLogin(this.usrname, this.pswd).subscribe(
      response => {
        this.mytoki = response.headers.get('Authorization');
        sessionStorage.setItem('token', this.mytoki);
        console.log('Connected');
      }, err => {
        // TODO
        // login errors
        // put token into nav component
      }, () => {
          this.visible = 'hide';
          this.toHide.emit(this.visible);
          this.usrname = '';
          this.pswd = '';
      }
    );
  }
}

1 个答案:

答案 0 :(得分:1)

在模式组件上声明您的@Output() myTokiDetails;

然后,例如,在设置sessionStorage之后,this.myTokiDetails.emit(this.mytoki)会广播该事件,并假设您使用选择器将其添加到父级,您将在此模式选择器上使用:<app-modal (myTokiDetails)="parentComponentFunction($event)"></app-modal>