【问题标题】:Pass values to parent component with eventemitter使用 eventemitter 将值传递给父组件
【发布时间】:2019-04-28 06:12:26
【问题描述】:

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

【问题讨论】:

  • 很多方法,例如使用返回值
  • @BertVerhees 我的“toHide eventemitter”已经包含一个字符串值,我想要实现的也是发送“mytoki”的值,但不知道该怎么做
  • 见下面Kellie的回答,这是一个很好的处理方法,另一种方法是创建一个帮助类来保存要返回的值,并返回帮助类。

标签: angular angular-event-emitter


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2020-04-26
    • 2018-05-01
    相关资源
    最近更新 更多