繁体   English   中英

“AppComponent”类型上不存在属性“alertService”和“options”

[英]Property 'alertService' and 'options' does not exist on type 'AppComponent'

我正在我的应用程序中实现警报服务,但是我收到错误Property 'alertService' does not exist on type 'AppComponent'Property 'options' does not exist on type 'AppComponent'

app.component.html:

<div class="form-group">
   <button [disabled]="frmSignup.invalid" type="submit" class="btn btn-primary btn-block font-weight-bold" 
   (click)="alertService.success('Success!!', options)">Submit</button>
</div>

app.component.ts:

export class AppComponent {
  public frmSignup: FormGroup;
  public message = "Congrats you have successfully created your account";

  constructor(private fb: FormBuilder) {
    this.frmSignup = this.createSignupForm();
  }

  createSignupForm(): FormGroup {
    return this.fb.group(
      {
       ........
      }
    );
  }

  submit() {
    // do signup or something
    console.log(this.frmSignup.value);
    alert(this.message);
  }

您需要在alertService的构造函数中显式注入AppComponent

constructor(private fb: FormBuilder, alertService: AlertService) {
    this.frmSignup = this.createSignupForm();
    this.alertService = alertService;
}

这些选项也需要在组件中设置为公共属性。


然而:

更好的选择是创建一个类方法,您可以在单击事件上调用它:

<div class="form-group">
   <button [disabled]="frmSignup.invalid" type="submit" class="btn btn-primary btn-block font-weight-bold" 
   (click)="handleClick()">Submit</button>
</div>
export class AppComponent {
  public frmSignup: FormGroup;
  public message = "Congrats you have successfully created your account";
  options = {};

  constructor(private fb: FormBuilder, private alertService: AlertService) {
    this.frmSignup = this.createSignupForm();
  }

  createSignupForm(): FormGroup {
    return this.fb.group(
      {
       ........
      }
    );
  }

  submit() {
    // do signup or something
    console.log(this.frmSignup.value);
    alert(this.message);
  }
  
  handleClick() {
    this.alertService.success('Success!!', options);
  }
}

注意:我不明白,为什么提交按钮不调用提交方法......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM