如何从子组件访问父组件值而不通过输入传递它?

时间:2016-04-09 09:40:28

标签: angular

我正在制作电子邮件模式,但我在实际发出http.post请求时遇到了问题。问题是post()正在子组件中执行,这意味着当函数实际运行时this.postUrl未定义。如何确保子组件可以访问this.postUrl而不将其作为输入传递给它?为什么我不想通过输入传递它的原因是子组件也在其他地方使用,使得postUrl太具体而不能用作输入,因为它只会被使用在这种情况下。

@Component({
  selector: 'modal-email',
  templateUrl: './app/assets/scripts/modules/modal/templates/modal-email/modal-email.component.html',
  styleUrls: ['./app/assets/scripts/modules/modal/templates/modal-email/modal-email.component.css'],
  inputs: [
    'model',
    'postUrl',
    'header',
    'text'
  ],
  directives: [FormInputWithButtonComponent],
  providers: [Http, HTTP_PROVIDERS]
})

export class ModalEmailComponent {

  constructor(private _http: Http) {

  }

  post() {

    // this.postUrl becomes undefined, this.model is defined since it also lives in the child component
    console.log(this.postUrl, this.model);

    this._http.post(this.postUrl, {email: this.model})
      .map(res => res.json())
      .subscribe(
        data => this.data = data,
        err => console.log(err)
      )
  }
}

ModalEmailComponent的使用方式如下:

<modal-email postUrl="localhost:3000/email"></modal-email>

modal-email谎言form-input-with-button>组件内:

<form-input-with-button [(model)]="email" type="email" [onSubmit]="post"></form-input-with-button>

子组件:

@Component({
  selector: 'form-input-with-button',
  templateUrl: './app/assets/scripts/modules/form-controls/form-input-with-button/form-input-with-button.component.html',
  styleUrls: ['./app/assets/scripts/modules/form-controls/form-input-with-button/form-input-with-button.component.css'],
  inputs: [
    'model',
    'onSubmit' // onSubmit is what calls the post function from ModalEmailComponent
  ],
  host: {
    '(input)': 'modelChange.emit($event.target.value)'
  }
})

export class FormInputWithButtonComponent {
  @Input() model: string;
  @Output() modelChange: EventEmitter = new EventEmitter();
}

FormInputWithButtonComponent模板:

<input [(ngModel)]="model" class="form-input-with-button">
<button (click)="onSubmit()" class="form-input-button">Submit</button>

编辑:您可以扩展组件吗?类似的东西:

export class FormInputWithButtonComponent extends ModalEmailComponent

当我试着说Cannot read property prototype of undefined时,我觉得这是不可能的。

1 个答案:

答案 0 :(得分:0)

我建议您做的是创建一个服务,您可以在其中存储postUrl的值,以便在孩子中可以访问它。另一方面,您可以使用Event Emitter,并将其设置如下:

在ChildComponent中:

onSubmit(){
  EventEmit.emit('get')    
}

EventEmit.subscribe(msg=>{
  http.post(msg)
})

在父母身上:

EventEmit.subscribe(msg=>

if (msg == 'get') EventEmit.emit(this.postUrl)

);

当然,这只是伪代码,因此您需要根据需要进行调整。