首页 > 解决方案 > 如何在联系表单的地址类数组中显示来自json的数据

问题描述

我在 p-dropdown、p-calendar 的 Demographics 中显示了来自 json 的数据,但我无法在联系人表单中显示它(p-dropdown、p-calendar、p-autosearch),因为地址(联系人类别)是数组格式人口统计不是。所以首先参考我的人口统计表格(它工作得很好)然后告诉我如何通过使用数组使用相同的格式显示。检查人口统计中的 getPerson() 方法然后告诉我我可以做什么联系?

人口统计.component.html

<form [formGroup]="userform" (ngSubmit)="onSubmit(userform.value)">

<div class="ui-fluid">

    <p-panel header="Demograhics">


        <div class="ui-inputgroup">

                <label for="email" class="ui-md-2 control-label">Birthdate</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-calendar [(ngModel)]="date3"  formControlName="birthdate"  [monthNavigator]="true" [yearNavigator]="true"   yearRange="1950:2030" [showIcon]="true" dateFormat="dd.mm.yy" name="calendar"></p-calendar> <span style="margin-left:35px">{{date3|date}}</span>       
                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['birthdate'].valid&&userform.controls['birthdate'].dirty">
                            <i class="fa fa-close"></i>
                        Birthdate is required
                        </div>                                
                    </div>
        </div>


        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Martial Status</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                                <p-dropdown [options]="Martials" formControlName="martialstatus" [(ngModel)]="selectedvalidid5" [style]="{'width':'150px'}" filter="true" name="something" placeholder="MartialStatus">
                                        <ng-template let-item pTemplate="selectedItem">


                                            <span style="vertical-align:middle">{{item.label}}</span>
                                        </ng-template>
                                        <ng-template let-Martial pTemplate="item">
                                            <div class="ui-helper-clearfix" style="position: relative;height: 25px;">

                                                <div style="font-size:14px;float:right;margin-top:4px">{{Martial.label}}</div>
                                            </div>
                                        </ng-template>
                                    </p-dropdown>          


                            </div>
                        </div>

                        <div class="ui-md-4">     
                            <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['martialstatus'].valid&&userform.controls['martialstatus'].dirty">
                                <i class="fa fa-close"></i>
                            Martial status is required
                            </div>


                    </div>
        </div>

 <div class="ui-inputgroup">

                <div class="ui-md-8 ui-md-offset-4">
                    <button pButton type="submit" label="Submit" [disabled]="!userform.valid"></button>
                        <button pButton type="button" (click)="count()" label="Cancel"></button>                           
                </div>
        </div>                     

    </p-panel>

</div>

</form>

人口统计.component.ts

import { Component, OnInit } from '@angular/core';
import * as jwt from 'angular2-jwt/angular2-jwt';
import { CardModule } from 'primeng/card';
import { CalendarModule } from 'primeng/calendar';
import { ScrollPanelModule } from 'primeng/scrollpanel';
import { Response } from '@angular/http/src/static_response';
import { CountryService} from './country-list.service';
import {SelectItem} from 'primeng/api';
import { Message } from 'primeng/components/common/api';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { PersonListService,Person, Demographic} from './person-list.service';
import { DatePipe } from '@angular/common';


@Component({ 
  moduleId: module.id,
  selector: 'sd-demographicform',
  templateUrl: 'demographicform.component.html',
  providers:[DatePipe],
  styleUrls: ['demographicform.component.css']
})
export class DemographicFormComponent implements OnInit {

  demographics: Demographic;

  //date3:string;
  date3:Date;
  dates: Date[];

  rangeDates: Date[];

  minDate: Date;

  maxDate: Date;
ValidIds: SelectItem[];

  selectedvalidid2: string = '';

  Religions: SelectItem[];

  selectedvalidid3: string = '';

  BloodGroups: SelectItem[];

  selectedvalidid4: string = '';

  Martials: SelectItem[];

  selectedvalidid5: string;

  country: any;

  filteredCountriesSingle: any[];

  msgs: Message[] = [];

  userform: FormGroup;

  submitted: boolean;

  constructor(private countryService: CountryService,private fb: FormBuilder,public personListService:PersonListService,private datePipe: DatePipe) { }
 ngOnInit() {

    this.getperson();
    //this.date3.setDate((new Date()).getDate() - 5);
    this.userform = this.fb.group({
        'nationality': new FormControl('', Validators.required),
        'birthdate': new FormControl('', Validators.required),
        'martialstatus': new FormControl('', Validators.required),
        'gender': new FormControl('', Validators.required),
        'height': new FormControl('', Validators.required),
        'valididtype': new FormControl('', Validators.required),
        'valididno': new FormControl('', Validators.required)

    }
);
  this.Martials = [
    {label: 'Married', value: 'Married'},
    {label: 'Unmarried', value: 'Unmarried'},
    {label: 'Divorced', value: 'Divorced'},
    {label: 'Widowed', value: 'Widowed'},
    {label: 'Separated', value: 'Separated'},
];
 getperson(){

        this.personListService.getDemographic()

        .subscribe(
         resp =>{
         this.demographics = resp.Demographics;
        // this.date3=new Date()
         this.date3 = new Date(this.demographics.Birthdate)
         this.selectedvalidid5=this.demographics.MartialStatus
         this.val2=this.demographics.Gender
         this.selectedvalidid2=this.demographics.ValidIdType
         this.selectedvalidid3=this.demographics.Religion
         this.selectedvalidid4=this.demographics.BloodGroup
        //this.selectedvalidid5=this.demographics.MartialStatus
          //resp => this.addresses = resp.Addresses,
         console.log(this.demographics.Birthdate)
    });


   }
    onSubmit(value: string) {
        this.submitted = true;
        this.msgs = [];
        this.msgs.push({severity:'info', summary:'Success', detail:'Form Submitted'});
    }
} 

contactform.component.html

 <form [formGroup]="address" (ngSubmit)="onSubmit(address.value)">

    <p-dataList [value]="addresses" [paginator]="true" [rows]="1">
            <p-header>
                        Addresses
            </p-header>

            <ng-template let-address let-i="index" pTemplate="item">

    <div class="ui-fluid">

    <div class="ui-inputgroup"> 

                <label for="email" class="ui-md-2 control-label">Address Type</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-dropdown [options]="AddressTypes"  name="something" formControlName="addresstype" [(ngModel)]="selectedvalidid6" [style]="{'width':'160px'}" filter="true" name="something" placeholder="Address Types">
                                    <ng-template let-item pTemplate="selectedItem">

                                        <span style="vertical-align:middle">{{ item.label }}</span>
                                    </ng-template>
                                    <ng-template let-AddressType pTemplate="item">
                                        <div class="ui-helper-clearfix" style="position: relative;height: 26px;">

                                            <div style="font-size:14px;float:right;margin-top:4px">{{ AddressType.label }}</div>
                                        </div>
                                    </ng-template>
                                </p-dropdown>

                        </div>

                    </div>

                   <div class="ui-md-4">     
                            <!--<div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['addresstype'].valid&&address.controls['addresstype'].dirty">
                                <i class="fa fa-close"></i>
                                addresstype is required
                            </div>-->
                    </div>
        </div>

        <div class="ui-inputgroup"> 

                    <label for="email" class="ui-md-2 control-label">Address L1</label>

                        <div class="ui-md-6">
                            <div class="ui-inputgroup">
                                <input type="text" pInputText pKeyFilter="alphanum" formControlName="addressl1" name="something" value="{{ this.address.AddressL1 }}" placeholder="Address L1"> 
                            </div>
                        </div>

                        <div class="ui-md-4">     
                                <!--<div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['addressl1'].valid&&address.controls['addressl1'].dirty">
                                    <i class="fa fa-close"></i>
                                    addressl1 is required
                                </div>-->
                        </div>
        </div>

     <div class="ui-inputgroup"> 

                <label for="email" class="ui-md-2 control-label">Address L2</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <input type="text" pInputText pKeyFilter="alphanum" name="something" formControlName="addressl2" value="{{ this.address.AddressL2 }}" placeholder="Address L2">
                        </div>
                    </div>

                    <div class="ui-md-4">     
                         <!--   <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['addressl2'].valid&&address.controls['addressl2'].dirty">
                                <i class="fa fa-close"></i>
                                addressl2 is required
                            </div>-->
                    </div>
        </div>


        <div class="ui-inputgroup"> 

                <label for="password" class="ui-md-2 control-label">State</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-autoComplete [(ngModel)]="state" [suggestions]="filteredStatesSingle" formControlName="state" (completeMethod)="filterStateSingle($event)" field="state" [size]="auto"
                            placeholder="State"  [minLength]="1" name="something">


                        </p-autoComplete>                    


                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <!--    <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['state'].valid&&address.controls['state'].dirty">
                                <i class="fa fa-close"></i>
                            State is required
                            </div>-->
                    </div >
        </div>

        <div class="ui-inputgroup"> 

                    <label for="password" class="ui-md-2 control-label">Locality</label>

                        <div class="ui-md-6">
                            <div class="ui-inputgroup">
                                <input type="text" pInputText pKeyFilter="alpha" name="something" formControlName="locality" value="{{ this.address.Locality }}" placeholder="Locality">

                            </div>
                        </div>

                        <div class="ui-md-4">     
                             <!--   <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['locality'].valid&&address.controls['locality'].dirty">
                                    <i class="fa fa-close"></i>
                                Locality is required
                                </div>-->
                        </div>
        </div>

        <div class="ui-inputgroup"> 

                <label for="password" class="ui-md-2 control-label">City</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-autoComplete [(ngModel)]="city" [suggestions]="filteredCitiesSingle" formControlName="city" (completeMethod)="filterCitySingle($event)" field="city" [size]="auto"
                            placeholder="City" [minLength]="1"  name="something"></p-autoComplete>                    

                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <!--    <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['city'].valid&&address.controls['city'].dirty">
                                <i class="fa fa-close"></i>
                            City is required
                            </div>-->
                    </div>
        </div>

        <div class="ui-inputgroup"> 

                <label for="password" class="ui-md-2 control-label">Country</label>

                    <div class="ui-md-6">

                                 <p-autoComplete [(ngModel)]="country" [suggestions]="filteredCountriesSingle" formControlName="country" (completeMethod)="filterCountrySingle($event)" field="country" [size]="auto"
                                placeholder="Country" [minLength]="1"  name="something"></p-autoComplete>                    
                                <span style="margin-left:10px">Country: {{country ? country.country||country : 'none'}}</span>


                    </div>

                    <div class="ui-md-4">     
                     <!--   <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['country'].valid&&address.controls['country'].dirty">
                                <i class="fa fa-close"></i>
                                country is required
                            </div>-->
                    </div>
        </div>

        <div class="ui-inputgroup"> 

                <label for="password" class="ui-md-2 control-label">Postal Code</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <input type="text" pInputText pKeyFilter="num" name="something" formControlName="postalcode" value="{{ this.address.Postalcode }}" placeholder="Postal Code">
                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <!--    <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!address.controls['postalcode'].valid&&address.controls['postalcode'].dirty">
                                <i class="fa fa-close"></i>
                                postalcode is required
                            </div>-->
                    </div>
        </div>

        <div class="ui-inputgroup">
                <div class="ui-md-8 ui-md-offset-4">

         <button pButton type="submit" label="Submit" [disabled]="!address.valid"></button>
            <button pButton type="button" (click)="count()" name="something" label="Add Another"></button>
            <button pButton type="button" (click)="count()" label="Cancel"></button>

        </div>
    </div> 
    </div>
    </ng-template>
    </p-dataList>
    </form>  

contactform.component.ts

 import { Component, OnInit } from '@angular/core';
    import * as jwt from 'angular2-jwt/angular2-jwt';
    import { CardModule } from 'primeng/card';
    import { CalendarModule } from 'primeng/calendar';
    import { ScrollPanelModule } from 'primeng/scrollpanel';
    import { Response } from '@angular/http/src/static_response';
    import { SelectItem } from 'primeng/api';
    import { CountryService } from './country-list.service';
    import { StateService } from './state-list.service';
    import { CityService } from './city-list.service';
    import { Console } from '@angular/core/src/console';
    import { Message } from 'primeng/components/common/api';
    import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
    import { PersonListService,Person, Address, Email, ContactNumber} from './person-list.service';
    import {DataListModule} from 'primeng/datalist';

    @Component({ 
      moduleId: module.id,
      selector: 'sd-contactform',
      templateUrl: 'contactform.component.html',
      styleUrls: ['contactform.component.css']
    })
    export class ContactFormComponent implements OnInit {

    addresses: Address[];

    selectedvalidid6: string = '';

    errorMessage: any;

    emails:Email[];

    contactnumbers:ContactNumber[];

      date3: Date;

      dates: Date[];

      rangeDates: Date[];

      minDate: Date;

      maxDate: Date;

      es: any;

      invalidDates: Array<Date>;

      val2: string = 'Male';

      val3: string = 'Unmarried';

      text: string;

      ValidIds: SelectItem[];

      selectedvalidid2: string = '';

      Religions: SelectItem[];

      selectedvalidid3: string = '';

      BloodGroups: SelectItem[];

      selectedvalidid4: string = '';

      AddressTypes: SelectItem[];

      selectedvalidid5: string = '';

      EmailTypes: SelectItem[];

      emailtype:string;

      ContactTypes: SelectItem[];

      selectedvalidid7: string = '';

      country: any;

      filteredCountriesSingle: any[];

      state: any;

      filteredStatesSingle: any[];

      city: any;

      filteredCitiesSingle: any[];

      msgs: Message[] = [];

      address: FormGroup;

      email: FormGroup;

      contact: FormGroup;

      submitted: boolean;

      constructor(public personListService:PersonListService,private countryService: CountryService,private stateService: StateService,private cityService: CityService,private fb: FormBuilder) { }

     getperson(){

            this.personListService.getAddress()
             .subscribe(
              resp => this.addresses = resp.Addresses,

               //resp => this.addresses = resp.Addresses,
              /// error => this.errorMessage = <any>error
             );
            this.personListService.getEmail()
             .subscribe(
              resp => this.emails = resp.Emails,

               //resp => this.addresses = resp.Addresses,
               //error => this.errorMessage = <any>error
             );
             this.personListService.getContact()
             .subscribe(
              resp => this.contactnumbers = resp.ContactNumbers,

               //resp => this.addresses = resp.Addresses,
               error => this.errorMessage = <any>error
             ); 
           }
        }

人.json

{

"Demographics" : {

            "ProfileId":1,
            "FirstName":"Vinit",
            "LastName":"Mapari",
            "Birthdate":"1996-05-05",
            "MartialStatus":"Unmarried",
            "Gender":"Male",
            "Height":"5ft2inch",
            "ValidIdType":"Pancard",
            "ValidIdNumber":"123",
            "Nationality":"Indian",
            "Religion":"Hindu",
            "BloodGroup":"A",
            "NearestRailwayStation":"Byculla"

        },

"Addresses": [{ 

            "AddressId":101,
            "AddressType":"Permanent",
            "AddressL1":"Mind space", 
            "AddressL2":"A.b.road",
            "Locality":"Airoli(east)",
            "City":"Mumbai", 
            "State":"Maharashtra",
            "Country":"India",
            "Postalcode":400011
         },
         { 

                "AddressId":102,
                "AddressType":"Permanent",
                "AddressL1":"Mind space1", 
                "AddressL2":"N.m.road",
                "Locality":"Pune(west)",
                "City":"Pune", 
                "State":"Maharashtra",
                "Country":"India",
                "Postalcode":400012
             }]
}

人员列表.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/operator/do';  // for debugging
export class Demographic{
  ProfileId:number;
  FirstName:string="";
  LastName:string="";
  Birthdate:string="";
  MartialStatus:string="";
  Gender:string="";
  Height:string="";
  ValidIdType:string="";
  ValidIdNumber:string="";
  Nationality:string="";
  Religion:string="";
  BloodGroup:string="";
  NearestRailwayStation:string="";
}
export class Address{
  AddressId:number;
  AddressType:string="";
  AddressL1:string=""; 
  AddressL2:string="";
  Locality:string="";
  City:string=""; 
  State:string="";
  Country:string="";
  Postalcode:number;
}
export class Person{

  Demographics:Demographic;

  Addresses:Address[];
}

/**
 * This class provides the NameList service with methods to read names and add names.
 */
@Injectable()
export class PersonListService {

  /**
   * Creates a new NameListService with the injected HttpClient.
   * @param {HttpClient} http - The injected HttpClient.
   * @constructor
   */
  constructor(private http: HttpClient) {}

  /**
   * Returns an Observable for the HTTP GET request for the JSON resource.
   * @return {string[]} The Observable for the HTTP request.
   */
  getDemographic(): Observable<{Demographics: Demographic }>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

                 // .do(data => console.log('server data:', data))  // debug
                    .catch(this.handleError);

  }

  getAddress(): Observable<{Addresses: Address[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

                 // .do(data => console.log('server data:', data))  // debug
                    .catch(this.handleError);

  }
private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    const errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

标签: angular

解决方案


推荐阅读