使用 eventemitter 将值传递给父组件

Pass values to parent component with eventemitter

如何将 '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 = '';
      }
    );
  }
}

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

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