【问题标题】:ERROR TypeError: this.user.setPassword is not a function in angular 5 ?错误类型错误:this.user.setPassword 不是角度 5 中的函数?
【发布时间】:2018-12-03 11:59:43
【问题描述】:

在前端使用一个简单的 angular5 应用程序,我想编辑配置文件 当用户想要时,我有一个与组件 ParametresComponent 相关的按钮设置。

我首先做的是用get UserInfo()函数显示用户信息,然后当用户完成修改他的帐户时,他可以保存更改,(他只能更改'Tel'和'password')。

所以我有一个类 Model User.ts :

export class  User{

  id:number;
  username:string;
  password:string;
  prenom:string;
  nom:string;
  tel:string;
  cin:string ;

  setId(value: number) {
    this.id = value;
  }

  setUsername(value: string) {
    this.username = value;
  }

  setPassword(value: string) {
    this.password = value;
  }

  setPrenom(value: string) {
    this.prenom = value;
  }

  setNom(value: string) {
    this.nom = value;
  }

  setTel(value: string) {
    this.tel = value;
  }

  setCin(value: string) {
    this.cin = value;
  }



}

参数Component.component.ts

import { Component, OnInit } from '@angular/core';
    import * as _swal from 'sweetalert';
    import { SweetAlert } from 'sweetalert/typings/core';
    import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
    import {ActivatedRoute, Router} from '@angular/router';
    import {User} from '../Admin/Models/User';
    import {Devloppeur} from '../Admin/Models/Devloppeur';
    import {DevloppeurService} from '../../../service/devloppeur.service';
    import {ClientService} from '../../../service/client.service';
    import {AuthenticationService} from '../../../service/authentication.service';
    const swal: SweetAlert = _swal as any;

    function passwordMatch(control: AbstractControl):{[key: string]: boolean}{

      const password = control.get('password');
      const Confirmationpassword = control.get('Confirmationpassword');

      if( !password || !Confirmationpassword) {
        return null; }

      if(password.value === Confirmationpassword.value){
        return null;
      }

      return {
        mismatch:true
      }

    }

    @Component({
      selector: 'app-parametres',
      templateUrl: './parametres.component.html',
      styleUrls: ['./parametres.component.scss']
    })
    export class ParametresComponent implements OnInit {

      form: FormGroup;
      user:User  = new User();
      id:number;
      constructor(private formBuilder: FormBuilder,
                  public router:Router,
                  private authService:AuthenticationService,
                  public activatedRoute:ActivatedRoute,
                  private devService:DevloppeurService,
                  private clientServ:ClientService) { }

      ngOnInit() {
        this.id = this.authService.getAuthenticatedUserId();
        this.getUserInfo();

        this.form = this.formBuilder.group({
          prenom: [''] ,
          nom: [''],
          tel: ['', Validators.required],
          cin: [''],
          username : [''],
          passwordG: this.formBuilder.group({
            password: ['',[Validators.required,Validators.minLength(9)]],
            Confirmationpassword : ['',[Validators.required,Validators.minLength(9)]]

          }, {validator: passwordMatch})

        });
      }

      getUserInfo(){
        this.clientServ.getUser(this.id)
          .subscribe((data:any)=>{
            this.user = data;
          },err=>{
            console.log('there is an error lady ! ');
          })

      }


      SaveEditUser(){
        this.user.setPassword(this.form.value.passwordG.password);
        this.user.setTel(this.form.value.tel);


        this.devService.saveUser(this.user)
          .subscribe((data:User)=>{
            swal("operation réussi !", "Great edited with success !", "success");
            this.router.navigate([ '/profil' ], { relativeTo: this.activatedRoute });
          },err=>{
            console.log(err);
          })
      }


    }

还有parametres.Component.html:

<div >
  <div class="col-sm-10">
    <div class="card">
      <div class="card-header">
        <strong>Modifier mon profil</strong>
      </div>

      <form [formGroup]="form" (ngSubmit)="SaveEditUser()">

        <div class="card-body">
          <div class="form-group">
            <label for="company">Prenom</label>
            <input type="text" class="form-control" id="company" disabled [(ngModel)]="user.prenom"  formControlName="prenom"/>
          </div>
          <div class="form-group">
            <label for="vat">Nom</label>
            <input type="text" class="form-control" id="vat"  disabled [(ngModel)]="user.nom"   formControlName="nom" />
          </div>
          <div class="form-group">
            <label for="vat">Tel</label>
            <input type="number" class="form-control" id="vat"  [(ngModel)]="user.tel"  formControlName="tel" />
          </div>
          <div class="form-group">
            <label for="vat">Cin</label>
            <input type="text" class="form-control" id="vat"   disabled [(ngModel)]="user.cin"  formControlName="cin" />
          </div>
          <div class="form-group">
            <label for="vat">Email</label>
            <input type="text" class="form-control" id="vat"   disabled [(ngModel)]="user.username"  formControlName="username" />
            <div class="error" *ngIf="form.controls['username'].invalid && form.controls['username'].errors.required && (form.controls['username'].dirty || form.controls['username'].touched)">Please enter an email</div>
            <div class="error" *ngIf="form.controls['username'].invalid && form.controls['username'].errors.email && (form.controls['username'].dirty || form.controls['username'].touched)">Please enter a valid email</div>
            <div class="error" *ngIf="form.controls['username'].invalid && form.controls['username'].errors.emailTaken">This email has been taken, please use another one.</div>
          </div>


          <div formGroupName = "passwordG">

            <div class="form-group">
              <label for="vat">Password</label>
              <input type="password" class="form-control" id="vat"    formControlName="password" />
            </div>

            <div class="form-group">
              <label for="vat">Confirmation Password</label>
              <input type="password" class="form-control" id="vat" formControlName="Confirmationpassword" />
            </div>


            <div *ngIf="(form.controls['passwordG'].invalid && form.controls['passwordG'].touched)" class="col-sm-3 text-danger">

              <ng-container *ngIf="form.controls['passwordG'].errors?.mismatch;
                then first else second"> </ng-container>

              <ng-template #first>
                Password do not match </ng-template>

              <ng-template #second>
                Password needs to be more than 8 characters
              </ng-template>
            </div>

          </div>

        </div>
        <div class="card-footer">
          <button type="submit" class="btn btn-sm btn-primary" [disabled] = "!form.valid"><i class="fa fa-dot-circle-o"></i>Enregistrer Les modifications</button>
        </div>
      </form>
    </div>
  </div><!--/.col-->
</div>

问题是保存时出现此错误:

ParametresComponent.html:8 ERROR TypeError: this.user.setPassword is not a function
    at ParametresComponent.SaveEditUser (parametres.component.ts:79)
    at Object.eval [as handleEvent] (ParametresComponent.html:8)
    at handleEvent (core.js:13530)
    at callWithDebugContext (core.js:15039)
    at Object.debugHandleEvent [as handleEvent] (core.js:14626)
    at dispatchEvent (core.js:9945)
    at eval (core.js:12284)
    at SafeSubscriber.schedulerFn [as _next] (core.js)

我无法理解为什么会出现此错误?任何想法 ?

【问题讨论】:

    标签: angular angular5 frontend


    【解决方案1】:

    尝试将所有方法的访问说明符设置为公开,

    public setPassword(value: string) {
        this.password = value;
    }
    

    【讨论】:

    【解决方案2】:

    我有两个建议:
    1)尝试在用户中添加一个构造函数。
    2) 在 getUserInfo() 中尝试将对象保存为用户类型

    getUserInfo(){
            this.clientServ.getUser(this.id)
              .subscribe((data:any)=>{
                this.user = data; // <-- this.user = data as User;
              },err=>{
                console.log('there is an error lady ! ');
              })
          }
    

    【讨论】:

    • 你可以保留它,重要的是添加:this.user = data as User;就像手动声明我们将此对象视为用户一样。让我知道它是否有效。
    【解决方案3】:

    您将从 API 获得的对象分配给 this.user 对象。这意味着您的新用户对象不再属于 User 类型,因为您无法在从 API 接收的对象上传递方法。如果您希望将 API 中的对象分配给您的 this.user,则必须保留调用 new User 的原始 this.user(从而在对象的原型上创建方法)。为此,您应该分配 API 对象的属性而不是对象本身:

    getUserInfo(){
      this.clientServ.getUser(this.id)
        .subscribe((data:any)=>{
          Object.assign(this.user, data);
        },err=>{
          console.log('there is an error lady ! ');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-18
      • 2020-04-14
      • 2022-01-21
      • 2019-11-30
      • 2019-10-07
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多