向后端返回的数据添加FormControl累积,但在Angular应用中出现两个不同的错误 [英] Add FormControl accroding to the data returned from backend but got two different error in Angular app

查看:56
本文介绍了向后端返回的数据添加FormControl累积,但在Angular应用中出现两个不同的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Angular应用程序的页面之一.

This is one of the page of my Angular app.

在ngOnInit方法中,我两次调用api以获取所需的不同数据,并使用forEach方法构建反应形式来遍历数据,但是不知何故,我遇到了两个不同的错误之一.

Inside the ngOnInit method, I call the api twice to get different data I need and loop through the data by using forEach method to build reactive form, but somehow, I encountered one of two different error.

在此处输入图片描述

还有这个

在此处输入图片描述

有时完全没有错误.

如果有人能告诉我我的代码有什么问题,将不胜感激.

It would be grateful if someone can tell me what's wrong with my code.

这是我的代码的一部分

user-manager.component.ts

user-manager.component.ts

export class UserManagerComponent implements OnInit {
    constructor(
    private fb: FormBuilder
  ) {}
    ngOnInit(): void {
        this.commonData.getDropdownData('menus')
        .pipe(takeWhile(() => this.alive))
        .subscribe(r => {
          if (r.status === 0) {
            this.menuForm = this.fb.group({});
            this.menuList = r.result.menus;
            this.menuList.forEach(i => {
              const control = new FormControl();
             (this.menuForm as FormGroup).setControl(i.MenuId, control);
              i.children.forEach(a => {
                const con = new FormControl();
                (this.menuForm as FormGroup).setControl(a.MenuId, con);
              });
            });
            this.isMenuFormReady = true;
      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.menuForm = this.fb.group({});
          this.menuList = menuMock.menus;
          this.menuList.forEach(i => {

            const control = new FormControl();

            (this.menuForm as FormGroup).setControl(i.MenuId, control);

            i.children.forEach(a => {
              const con = new FormControl();
              (this.menuForm as FormGroup).setControl(a.MenuId, con);
            });

          });
          this.isMenuFormReady = true;
        }
          console.log(error);
      });

    this.commonData.getDropdownData('permissions')
    .pipe(takeWhile(() => this.alive))
    .subscribe(r => {
      if (r.status === 0) {
        this.permissionsForm = this.fb.group({});
        this.permissionsList = r.result;
        this.permissionsList = this.groupBy(this.permissionsList, function(item) {
          return [item.GroupId];
      });

      this.permissionsList.forEach(i => {

        const id = i[0].GroupId;
        this.permissionsForm.addControl(id, this.fb.group({}));

        i.forEach(a => {
          const con = new FormControl();
          (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
        });
      });
      this.isPermissionFormReady = true;

      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.permissionsForm = this.fb.group({});
          this.permissionsList = userMock.Permission;
          this.permissionsList = this.groupBy(this.permissionsList, function(item) {
            return [item.GroupId];
        });

          this.permissionsList.forEach(i => {

            const id = i[0].GroupId;
            // console.log('id: ', id)
            this.permissionsForm.addControl(id, this.fb.group({}));

            i.forEach(a => {
              const con = new FormControl();
              (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
            });
          });
          this.isPermissionFormReady = true;
          // console.log(this.permissionsForm);
        }
          console.log(error);
      });
  }
    groupBy( array , f ) {
        const groups = {};
        array.forEach( function(o) {
            const group = JSON.stringify( f(o) );
            groups[group] = groups[group] || [];
            groups[group].push( o );
        });
        return Object.keys(groups).map( function( group ) {
            return groups[group];
        });
    }
}

user-manager.component.html

user-manager.component.html

      <nb-card>

          <nb-card-header>
            form1
          </nb-card-header>
          <nb-card-body>
              <form [formGroup]="permissionsForm" autocomplete="off" *ngIf="isPermissionFormReady">
            <nb-card *ngFor="let item of permissionsList; let i = index;" [formGroupName]="i">
              <nb-card-header>
                {{item[0].GroupName}}
              </nb-card-header>
              <nb-card-body class="pt-0">
                <div class="row">
                  <div class="col-4 my-1" *ngFor="let permission of item">
                    <label>
                      <input type="checkbox" [formControlName]="permission.ActionId"/>
                      {{permission.ActionName}}
                    </label>
                  </div>
                </div>
              </nb-card-body>
            </nb-card>
          </form>
          </nb-card-body>

        </nb-card>

        <nb-card>
            <nb-card-header>
              form2
            </nb-card-header>
            <nb-card-body>
              <form [formGroup]="menuForm" autocomplete="off" *ngIf="isMenuFormReady">
                <div class="row">
                    <div class="col-4" *ngFor="let menu of menuList" >
                        <nb-card>
                          <nb-card-header>
                            <label>
                              <input type="checkbox" id="{{menu.MenuId}}" [formControlName]="menu.MenuId" (change)="menuClick($event)"/>
                              {{menu.title}}
                            </label>
                          </nb-card-header>
                          <nb-card-body class="pt-0">
                            <div class="row">
                              <div class="col-12 my-1" *ngFor="let item of menu.children">
                                <label>
                                  <input type="checkbox" id="{{item.MenuId}}" [formControlName]="item.MenuId" (change)="menuClick($event)"/>
                                  {{item.title}}
                                </label>
                              </div>
                            </div>
                          </nb-card-body>
                        </nb-card>
                      </div>
                </div>
              </form>
            </nb-card-body>
          </nb-card>

推荐答案

Chrome 80当前存在一个错误,该错误使Array.reduce无法按照规范运行.因此,如果您在项目中使用反应形式,则将遇到浏览器特定的问题,例如(form.get('key').value未定义或valuechanges即使存在也未定义),在chrome 79中可以正常工作.要解决此问题,请按如下所示在您的角度项目中手动添加Array.reduce polyfill.

There is currently a bug in Chrome 80 which makes Array.reduce not to work according to the spec. So If you are using reactive form in your project you will face browser specific issue like ( form.get('key').value is undefined or valuechanges is undefined even if it exists), which was working fine in chrome 79. To fix this issue, add Array.reduce polyfill in your angular project manually as shown below.

将此添加到 main.ts

(function () {
 function getChromeVersion() {
 const raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);

 return raw ? parseInt(raw[2], 10) : false;
    }

 const chromeVersion = getChromeVersion();
 if (chromeVersion && chromeVersion >= 80) {
      Array.prototype.reduce = function (callback /*, initialValue*/) {
 'use strict';
 if (this == null) {
 throw new TypeError('Array.prototype.reduce called on null or undefined');
        }
 if (typeof callback !== 'function') {
 throw new TypeError(callback + ' is not a function');
        }
 let t = Object(this), len = t.length >>> 0, k = 0, value;
 if (arguments.length === 2) {
          value = arguments[1];
        } else {
 while (k < len && !(k in t)) {
            k++;
          }
 if (k >= len) {
 throw new TypeError('Reduce of empty array with no initial value');
          }
          value = t[k++];
        }
 for (; k < len; k++) {
 if (k in t) {
            value = callback(value, t[k], k, t);
          }
        }
 return value;
      };
    }
  })();

ForMoreInfo

这篇关于向后端返回的数据添加FormControl累积,但在Angular应用中出现两个不同的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆