TypeError:无法读取空角度6的属性“ postalCode”

时间:2019-01-23 10:35:45

标签: angular angular6 model-binding angular-template-form

在我的应用程序中,我获得了用户的名字,姓氏,电子邮件,手机和密码。在“用户帐户信息”页面中,显示字段firstName,lastName,手机,性别,电子邮件,street1,street2,省,郊区,postalCode。当我转到“帐户信息”页面时,它仅显示名字,姓氏,电子邮件,手机和性别。 下面给出了立即注册的用户从API获取数据的方式。

data: {customerId: "398",…}
attributes: {id: 398, firstName: "Jhon", middleName: null, lastName: 
"Doile", mobile: "9471123456",…}
 address: null
 dob: null
 email: "nirdima@gmail.com"
 firstName: "John"
 fullName: "Jhon Doile"
 gender: null
 id: 398
 lastAccessAt: "2019-01-23 08:37:20"
 lastLoginAt: "2019-01-23 08:37:20"
 lastName: "Doile"
 locale: null
 middleName: null
 mobile: "9471123456"
 phone: null
 profilePic: null
 sendNews: 0
 status: 2
 timeZone: null
 customerId: "398"

但是,如果有任何地址数据,地址将在属性中显示为对象。我在每个未显示的字段的div中设置了* ngIf =“ model.address”。我需要一种显示隐藏字段的方法。如果我从一个字段(postalCode)中删除* ngIf =“ model.address”,则会出现错误“ TypeError:无法读取null的属性” postalCode”。我的模板已在下面显示。

 <form name="form" #f="ngForm" novalidate>
      <div class="form-row">
        <div class="form-group col-5">
          <label for="firstName">First Name<span class="require-span">* 
  </span></label>
          <input #firstName="ngModel"
                 id="firstName"
                 [(ngModel)]="model.firstName"
                 [ngClass]="{ 'is-invalid': f.submitted && firstName.invalid }"
                 class="form-control"
                 name="firstName"
                 placeholder="eg :- Jhon"
                 required
                 type="text"/>
          <div *ngIf="firstName.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="firstName.errors.required">First Name is required</div>
          </div>
        </div>
        <div class="form-group col-7">
          <label for="lastName">Last Name<span class="require-span">*</span></label>
          <input #lastName="ngModel" [(ngModel)]="model.lastName"
                 [ngClass]="{ 'is-invalid': f.submitted && lastName.invalid }" class="form-control" id="lastName"
                 name="lastName"
                 placeholder="eg :- Doe" required type="text"/>
          <div *ngIf="lastName.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="lastName.errors.required">Last Name is required</div>
          </div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group col-8">
          <label for="mobile">Mobile Number<span class="require-span">*</span></label>
          <div class="form-text-regMobile">
            <input #mobile="ngModel" (mobileNumberChange)="mobileNumberChange()" [(ngModel)]="model.mobile"
                   [ngClass]="{ 'is-invalid':  f.submitted && (mobile.invalid || !mobileValid ) }"
                   [ngClass]="{ 'is-invalid':  f.submitted && (mobile.invalid || !mobileValid ) }"
                   class="form-control" disabled
                   disabled
                   id="mobile"
                   name="mobile"
                   required type="tel"/>
            <!--<label for="mobile" class="static-value">94</label>-->
          </div>
          <div *ngIf="f.submitted && (mobile.invalid || !mobileValid )" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="mobile.errors.required">Mobile number is required.</div>
            <div *ngIf="!mobileValid">Provide us a valid mobile number/email. (eg : 0777123456 , 777123456).</div>
          </div>
        </div>
        <div class="form-group col-4">
          <label for="gender">Gender</label>
          <select id="gender" class="form-control form-control-select"
                  #gender="ngModel"
                  [(ngModel)]="model.gender"
                  name="gender"
                  [ngClass]="{ 'is-invalid': f.submitted && gender.invalid }">
            <option selected value="0">Male</option>
            <option  value="1">Female</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label for="email">Email Address<span class="require-span">*</span></label>
        <input #email="ngModel"
               [(ngModel)]="model.email"
               [ngClass]="{ 'is-invalid': f.submitted &&  email.invalid }"
               class="form-control"
               disabled
               id="email"
               name="email"
               required
               type="text"/>
        <div *ngIf="f.submitted && email.invalid" class="invalid-feedback">
          <i class="warning-icon"></i>
          <div *ngIf="email.errors.required">Email is required</div>
        </div>
      </div>

      <hr>
      <div class="form-row">
        <div class="form-group col-5" *ngIf="model.address">
          <label for="street1">Address Line 1<span class="require-span">*</span></label>
          <input #street1="ngModel" [(ngModel)]="model.address.street1"
                 [ngClass]="{ 'is-invalid': f.submitted && street1.invalid }"
                 class="form-control" id="street1"
                 name="street1"
                 placeholder="eg :- No.255"
                 type="text"
                 pattern="^[0-9a-zA-Z./]+$"
                 required/>
          <div *ngIf="street1.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="street1.errors.pattern">Enter a valid address line.</div>
            <div *ngIf="street1.errors.required">Address line is required.</div>
          </div>
        </div>
        <div class="form-group col-7" *ngIf="model.address">
          <label for="street2">Address Line 2</label>
          <input #street2="ngModel" [(ngModel)]="model.address.street2"
                 [ngClass]="{ 'is-invalid': f.submitted && street2.invalid }"
                 class="form-control" id="street2"
                 name="street2"
                 placeholder="eg :- Arcade Building, York Street"
                 type="text"
                 pattern="^[a-zA-Z./, ]+$"/>
          <div *ngIf="street2.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="street2.errors.pattern">Enter a valid address line.</div>
          </div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group col-6" *ngIf="model.address">
          <label for="province">Province<span class="require-span">*</span></label>
          <select id="province" class="form-control form-control-select"
                  #provinceId="ngModel" [(ngModel)]="model.address.provinceId" name="provinceId"
                  [ngClass]="{ 'is-invalid': f.submitted && provinceId.invalid }" required>
            <option value="1">Western Province</option>
            <option value="2">Central Province</option>
            <option value="3">Southern Province</option>
            <option value="4">Sabaragamuwa Province</option>
            <option value="5">NorthWestern Province</option>
            <option value="6">Eastern Province</option>
            <option value="7">Northern Province</option>
            <option value="8">Uva Province</option>
            <option value="9">NorthCentral Province</option>
          </select>
          <div *ngIf="provinceId.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="provinceId.errors.required">Province is required.</div>
          </div>
        </div>
        <div class="form-group col-6" *ngIf="model.address">
          <label for="city">District<span class="require-span">*</span></label>
          <select
            id="city"
            class="form-control form-control-select"
            #districtId="ngModel" [(ngModel)]="model.address.cityId"
            [ngClass]="{ 'is-invalid': f.submitted && districtId.invalid }"
            name="districtId" required>
            <option value="1">Colombo</option>
            <option value="2">Gampaha</option>
            <option value="3">Kaluthara</option>
            <option value="4">Nuwaraeliya</option>
            <option value="5">Kandy</option>
            <option value="6">Matale</option>

          </select>
          <div *ngIf="districtId.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="districtId.errors.required">District is required.</div>
          </div>
        </div>
      </div>

      <div class="form-row">
        <div class="form-group col-6" *ngIf="model.address">

          <label for="city">City<span class="require-span">*</span></label>

          <select id="suburb"
                  name="suburbId"
                  class="form-control form-control-select"
                  #suburbId="ngModel" [(ngModel)]="model.address.suburbId"
                  [ngClass]="{ 'is-invalid': f.submitted && suburbId.invalid }" required>
            <option value="45">Aggona</option>
            <option value="80">Ambalangoda</option>
            <option value="89">Ampara</option>
            <option value="37">Angoda</option>
            <option value="51">Angulana</option>

          </select>
          <div *ngIf="suburbId.invalid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="suburbId.errors.required">City is required.</div>
          </div>
        </div>
        <div class="form-group col-6">
          <label for="postalCode">Postal Code<span class="require-span">*</span></label>
          <input #postalCode ngModel [(ngModel)]="model?.address.postalCode"
                 [ngClass]="{ 'is-invalid': f.submitted && postalCode.invalid }" class="form-control"
                 id="postalCode"
                 name="postalCode"
                 placeholder="eg :- 00100" type="text"
                 pattern="[0-9]*"
                 required
          />
          <div *ngIf="!postalCode.valid" class="invalid-feedback">
            <i class="warning-icon"></i>
            <div *ngIf="postalCode.errors?.pattern">PostalCode should be a number.</div>
            <div *ngIf="postalCode.errors?.required">Postal Code is required.</div>
          </div>
        </div>
      </div>


      <div class="form-row">

        <div class="form-group col-lg-4 col-12 form-btn profile-btn" *ngIf="!editProfileClicked">
          <button class="btn edit-btn" (click)="editUser()" type="submit" name="edit">Edit
          </button>
        </div>
        <div class="form-group col-lg-4 col-12 form-btn profile-btn" *ngIf="editProfileClicked">
          <button (click)="f.form.valid && f.form.dirty && updateUser()" type="submit" name="save"
                  class="btn save-btn">Save
          </button>
          <button (click)="resetUserForm()" type="button" name="cancel"
                  class="btn cancel-btn">Cancel</button>

        </div>
      </div>
    </form>

我的.ts文件如下。

model: any = {};
dbModel: any = {};

 ngOnInit() {
  this.getUser();
 }

getUser() {
this.userAuthenticationService.getUser().subscribe(response => {
  this.originalUser = (<any>response).data.attributes;
  this.model = Object.assign({}, this.originalUser);
  console.log(this.model);
  this.cdc.detectChanges();
});
}

 onSubmit() {
 this.dbModel = {
  "firstName": this.model.firstName,
  "lastName": this.model.lastName,
  "gender":this.model.gender,
  "dob":this.model.gender,
  "street1":this.model.address.street1,
  "street2": this.model.address.street2,
  "postalCode":this.model.address.postalCode,
  "provinceId": this.model.address.provinceId,
  "districtId": this.model.address.cityId,
  "suburbId": this.model.address.suburbId
}
   this.userService.update(this.dbModel)
  .subscribe(success => {
    this.toastyService.success('User profile updated successfully', 'Success:');
    // this.authService.logout().subscribe();
  }, error => {
    this.toastyService.error('User profile could not be updated', 'Error:');
  });
}

如果我在postalCode的div标签中添加* ngIf =“ model.address”,则不会给出错误,但不会显示。

1 个答案:

答案 0 :(得分:0)

该错误是由于API传递的地址= null,所以现在我通过在ngOnInit中传递一个对象作为波纹管来加载个人资料帐户信息页面时,传递的是空字符串和零值。

function fill_error(&$item,$key) {
    $item = "$key is required and cannot be null";
}
$rows = [
    'name'=> '',
    'tel' => '',
    'field' => 'someVal'
];


$errors = array_filter($rows,function($val) {
    return empty($val);
});
array_walk($errors,"fill_error");

我还修改了getUser方法。

ngOnInit() {
 this.model.address = {
  street1: '',
  street2: '',
  cityId: 0,
  suburbId: 0,
  provinceId: 0,
  postalCode: ''
 };
}

如果有更好的答案,或者这不是解决此问题的好方法,请在此处提及。