【发布时间】:2016-04-09 18:35:37
【问题描述】:
我正在制作电子邮件模式,但在实际发出 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 这让我觉得这是不可能的。
【问题讨论】:
-
我认为还不支持继承(我可能错了)。
标签: angular