【问题标题】:Property 'alertService' and 'options' does not exist on type 'AppComponent'“AppComponent”类型上不存在属性“alertService”和“选项”
【发布时间】:2020-08-27 06:57:33
【问题描述】:

我正在我的应用程序中实现警报服务,但是我收到错误 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);
  }

【问题讨论】:

    标签: javascript html json angular


    【解决方案1】:

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

    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);
      }
    }
    

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

    【讨论】:

    • 感谢 Argee 帮助我处理事件以及您对 handleClick() 函数的建议:)
    猜你喜欢
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    相关资源
    最近更新 更多