Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我想将数据转换为已注册成员的形式?_Javascript_Angular_Firebase - Fatal编程技术网

Javascript 我想将数据转换为已注册成员的形式?

Javascript 我想将数据转换为已注册成员的形式?,javascript,angular,firebase,Javascript,Angular,Firebase,我有一个表单,当我提交表单时,表单数据将提交到angular firebase数据库。因此,如果我们再次登录,我希望将数据显示到以前提交的表单中 我的.ts文件在下面 import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder,Validators } from "@angular/forms"; import { AF } from "app/providers/af"; import {

我有一个表单,当我提交表单时,表单数据将提交到angular firebase数据库。因此,如果我们再次登录,我希望将数据显示到以前提交的表单中

我的.ts文件在下面

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder,Validators } from "@angular/forms";
import { AF } from "app/providers/af";
import { FirebseService } from "app/firebse.service";
import { Router } from "@angular/router";
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

@Component({
  selector: 'app-candidate-registration',
  templateUrl: './candidate-registration.component.html',
  styleUrls: ['./candidate-registration.component.css']
})
export class CandidateRegistrationComponent implements OnInit {
  itemsAsObjects = [{value: 0, display: 'Angular'}, {value: 1, display: 'React'}];
  complexForm : FormGroup;
  contents:any;


  constructor(fb: FormBuilder,
               private firebaseService:FirebseService,
               private router: Router,
               private db: AngularFireDatabase) {

                var Userid=localStorage.getItem('user');
                console.log(Userid); 
                let content= this.db.object('/candidates_list/'+Userid)
                content.subscribe(data => {
                          console.log(data);
                          this.contents=data;
                          console.log(this.contents);
                        })
     if(this.contents){
        this.complexForm = fb.group({
      // To add a validator, we must first convert the string value into an array. The first item in the array is the default value if any, then the next item in the array is the validator. Here we are adding a required validator meaning that the firstName attribute must have a value in it.
              'firstName' : ["pranav", Validators.required],
              // We can use more than one validator per field. If we want to use more than one validator we have to wrap our array of validators with a Validators.compose function. Here we are using a required, minimum length and maximum length validator.
              'lastName': ["kk", Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(10)])],
              'gender' : [null, Validators.required],
              'email' : [null, Validators.required],
              'contact_number':[null, Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(10)])],
              'experience':[null, Validators.required],
              'skills':[null, Validators.required],
              'notice_period':[null, Validators.required],


            })
    }else
            {
              this.complexForm = fb.group({
              // To add a validator, we must first convert the string value into an array. The first item in the array is the default value if any, then the next item in the array is the validator. Here we are adding a required validator meaning that the firstName attribute must have a value in it.
              'firstName' : [null, Validators.required],
              // We can use more than one validator per field. If we want to use more than one validator we have to wrap our array of validators with a Validators.compose function. Here we are using a required, minimum length and maximum length validator.
              'lastName': [null, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(10)])],
              'gender' : [null, Validators.required],
              'email' : [null, Validators.required],
              'contact_number':[null, Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(10)])],
              'experience':[null, Validators.required],
              'skills':[null, Validators.required],
              'notice_period':[null, Validators.required],


            })
    }


  }

  ngOnInit() {


  }
  submitForm(user){

       console.log(user);
       this.firebaseService.addtolist(user);
       this.complexForm .reset();
       this.router.navigate(['/reg-complete']);


  }

}
下面的代码(是.ts文件的一部分)工作正常。我正在将已登录用户的数据输入控制台。但我不知道如何将其用于if条件,以便将已登录用户的数据设置到注册表中。 有人能帮我吗?先谢谢

var Userid=localStorage.getItem('user');
                    console.log(Userid); 
                    let content= this.db.object('/candidates_list/'+Userid)
                    content.subscribe(data => {
                              console.log(data);
                              this.contents=data;
                              console.log(this.contents);
                            })

好吧,这里的主要问题是当你检查这个声明时:

if (this.contents) { ... }
它将始终转到
其他

为什么??因为定义
this.contents
async
操作尚未解决,并且由于没有为
this.contents
定义初始值,因此未定义

我建议你查一查详细的解释


也就是说,我想提出另一种解决问题的方法:

与其让if/else包含完全重复的代码,不如将其分解为一个方法,如下所示:

initForm(data: Object = {}) {
  this.complexForm = fb.group({
    firstName: [data.firstName, Validators.required],
    lastName: [data.lastName, [Validators.required, Validators.minLength(1), Validators.maxLength(10)],
    gender: [data.gender, Validators.required],
    email: [data.email, Validators.required],
    contact_number: [data.contact_number, [Validators.required, Validators.minLength(10), Validators.maxLength(10)],
    experience: [data.experience, Validators.required],
    skills: [data.skills, Validators.required],
    notice_period: [data.notice_period, Validators.required]
  });
}
说明:

在签名方法中,我正在将
数据
初始化为一个干净的对象,因此如果nothing
undefined | null
传递给
函数
,它将自动成为像这样的干净对象

它很有用,因为它可以防止
未定义的错误。
错误

完整代码:

constructor(private fb: FormBuilder,
            private router: Router,
            private db: AngularFireDatabase,
            private firebaseService:FirebseService) {
  const userId = localStorage.getItem('user');

  if (userId) {
    this.db.object(`/candidates_list/${userId}`)
    .subscribe(data => {
      this.contents = data; // This variable isn't used anymore.
      this.initForm(data);
    });
  } else {
    this.initForm();
  }
}

initForm(data: Object = {}) {
  this.complexForm = fb.group({
    firstName: [data.firstName, Validators.required],
    lastName: [data.lastName, [Validators.required, Validators.minLength(1), Validators.maxLength(10)],
    gender: [data.gender, Validators.required],
    email: [data.email, Validators.required],
    contact_number: [data.contact_number, [Validators.required, Validators.minLength(10), Validators.maxLength(10)],
    experience: [data.experience, Validators.required],
    skills: [data.skills, Validators.required],
    notice_period: [data.notice_period, Validators.required]
  });
}
注意事项:

import 'rxjs/add/operator/finally';

...

isLoading: boolean = true;

...

this.db.object(`/candidates_list/${userId}`)
.finally(() => this.isLoading = false)
.subscribe(data => {
  this.contents = data;
  this.initForm(data);
});
<ng-container *ngIf="!isLoading">
  <form [formGroup]="complexForm">
    ...
  </form>
</ng-container>
1-不需要
Validators.compose
,您可以在两个参数(第2个和第3个)中传递一个数组,或者如果它是单个验证器,则传递验证器本身

2-我建议您将此代码从
constructor
移动到
ngOnInit

3-您可能会在模板中遇到一些错误,因为在解决async操作之前,
complexForm
不会被填充(当然,当您存储了用户时)

更具体地说,它将抛出以下错误:

原始异常:formGroup需要一个formGroup实例。请 把一个传进来

因此,您必须使用一些标志来处理模板中的表单

假设您的模板中有类似的内容:

<form [formGroup]="complexForm">
  ...
</form>
模板:

import 'rxjs/add/operator/finally';

...

isLoading: boolean = true;

...

this.db.object(`/candidates_list/${userId}`)
.finally(() => this.isLoading = false)
.subscribe(data => {
  this.contents = data;
  this.initForm(data);
});
<ng-container *ngIf="!isLoading">
  <form [formGroup]="complexForm">
    ...
  </form>
</ng-container>

...

您是否尝试过
设置值()
?您可以使用
this.complexForm.setValue()
使用从HTTP get获取的数据设置表单字段。