如何从json文件中支付json数据

时间:2018-09-01 14:31:36

标签: angular

我有person.json文件,其中包含人员数据。我正在使用angular进行编码,并在html中显示json数据,但无法显示。我在person-list.service中使用了人员类。 ts并在ts文件中返回this.persons。请帮助我。

person.component.html

<p-growl [value]="msgs" sticky="sticky"></p-growl>

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

<div class="ui-fluid">

    <p-panel header="Personal Information">

        <div class="ui-inputgroup"> 

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

                    <div class="ui-md-6">
                            <div class="ui-inputgroup">
                                <input type="text" size="30"  name="something" value="{{ this.persons.FirstName }}" pInputText>      
                            </div>
                    </div>
        </div>

        <div class="ui-inputgroup">

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

                        <div class="ui-md-6">
                                    <div class="ui-inputgroup">
                                        <input id="float-input" type="text" size="30" name="something" value="{{ this.LastName }}" pInputText>     
                                    </div>
                        </div>
        </div>


        <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">

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

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-radioButton name="group2" value="Male" formControlName="gender" label="Male"  [(ngModel)]="val2" inputId="preopt1" name="something"></p-radioButton>
                            <p-radioButton name="group2" value="Female" formControlName="gender" label="Female"  [(ngModel)]="val2" inputId="preopt2" name="something"></p-radioButton>
                        </div>
                    </div>

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


                </div>
        </div>

        <div class="ui-inputgroup">

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

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <span class="ui-float-label"> 
                                <input id="float-input" type="text" size="30" formControlName="height" value="{{ this.Height }}" name="something" pInputText>
                                <label for="float-input">height eg.5ft2inches</label>
                            </span>


                        </div>


                    </div>

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


                </div>
        </div>

        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Valid Id Types</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                                <p-dropdown [options]="ValidIds"  formControlName="valididtype" [(ngModel)]="selectedvalidid2" [style]="{'width':'150px'}" filter="true" name="something" placeholder="Valid Id Types">
                                        <ng-template let-item pTemplate="selectedItem">


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

                                                <div style="font-size:14px;float:right;margin-top:4px">{{ValidId.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['valididtype'].valid&&userform.controls['valididtype'].dirty">
                                <i class="fa fa-close"></i>
                            Valid Id type is required
                            </div>


                    </div>

                    </div>


        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Valid Id Number</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <input type="text" pInputText pKeyFilter="alphanum" placeholder="Valid Id Number" value="{{ this.ValidIdNumber }}" formControlName="valididno" name="something">
                        </div>

                    </div>

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


                </div>
        </div>

        <div class="ui-inputgroup">

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

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

                            <input type="text" pInputText pKeyFilter="alpha" formControlName="nationality" value="{{ this.Nationality }}" placeholder="Nationality">
                        </div>
                        <div class="ui-md-3">     
                            <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['nationality'].valid&&userform.controls['nationality'].dirty">
                                <i class="fa fa-close"></i>
                            Nationality is required
                            </div>


                    </div>
        </div>

        <div class="ui-inputgroup">

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

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                                <p-dropdown [options]="Religions"  [(ngModel)]="selectedvalidid3" [style]="{'width':'150px'}" [ngModelOptions]="{standalone: true}" filter="true" name="something" placeholder="Religion">
                                        <ng-template let-item pTemplate="selectedItem">


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

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

                        </div>
                    </div>


        </div>


        <div class="ui-inputgroup">

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

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                                <p-dropdown [options]="BloodGroups" [(ngModel)]="selectedvalidid4" [style]="{'width':'150px'}" [ngModelOptions]="{standalone: true}" filter="true" name="something" placeholder="BloodGroup">
                                        <ng-template let-item pTemplate="selectedItem">


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

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

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

        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Nearest Railway Station</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <input type="text" pInputText pKeyFilter="alpha" name="something" value="{{ this.NearestRailwayStation }}" placeholder="Nearest Railway Station">
                        </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>

person.component.ts

import { Component, OnInit } from '@angular/core';
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} from './person-list.service';
import { DatePipe } from '@angular/common';

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

  persons: Person;
  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 = '';
  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) { }

  filterCountrySingle(event) {
      let query = event.query;
      this.countryService.getCountries().then(countries => {
          this.filteredCountriesSingle = this.filterCountry(query, countries);
      });
  }

  filterCountry(query, countries: any[]):any[] {
    //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
    let filtered : any[] = [];
    for(let i = 0; i < countries.length; i++) {
        let country = countries[i];
        if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
            filtered.push(country);
        }
    }
    return filtered;
}
  ngOnInit() {

    this.getperson();

    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.ValidIds = [
      {label: 'Adharcard', value: 'Adharcard'},
      {label: 'Pancard', value: 'Pancard'},
      {label: 'Driving Lincense', value: 'DrivingLincense'},
      {label: 'Passport', value: 'Passport'}   
  ];

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

  this.Religions = [
    {label: 'Hindu', value: 'Hindu'},
    {label: 'Islam', value: 'Islam'},
    {label: 'Christianity', value: 'Christianity'},
    {label: 'Sikhism', value: 'Sikhism'},
    {label: 'Buddhism', value: 'Buddhism'},
    {label: 'Jainism', value: 'Jainism'}
];

this.BloodGroups = [
  {label: 'A', value: 'A'},
  {label: 'A+', value: 'A+'},
  {label: 'B', value: 'B'},
  {label: 'C', value: 'C'},
  {label: 'AB', value: 'AB'},
  {label: 'O', value: 'O'} 
]; 
}
    getperson(){

        this.personListService.getPersonalInformation()

        .subscribe(
         resp =>{
         this.persons = resp.Persons;
         this.date3 = new Date(this.persons.Birthdate)
         this.selectedvalidid5=this.persons.MartialStatus
         this.val2=this.persons.Gender
         this.selectedvalidid2=this.persons.ValidIdType
         this.selectedvalidid3=this.persons.Religion
         this.selectedvalidid4=this.persons.BloodGroup
    });     
   }
    onSubmit(value: string) {
        this.submitted = true;
        this.msgs = [];
        this.msgs.push({severity:'info', summary:'Success', detail:'Form Submitted'});
    }
}      

person.json

{
    "PersonId": 1,
    "FirstName": "Vinit",
    "LastName": "Mapari",
    "Birthdate": "1996-05-05",
    "MartialStatus": "Unmarried",
    "Gender": "Male",
    "Height": "5ft2inch",
    "ValidIdType": "Pancard",
    "ValidIdNumber": "123",
    "Nationality": "Indian"

}

person-list.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
export class Person{

  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="";
 }

/**
 * 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.
   */
  getPersonalInformation(): Observable<{Persons: Person }>{
    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);
  }
}

1 个答案:

答案 0 :(得分:0)

我猜您正在使用版本4或更高版本,如果是这样,请转至angular.json或angular-cli.json并找到名为Assets的部分,应该已经有几个条目。将路径添加到您的json文件中。

所以资产看起来像;

"assets": [
              "src/assets",
              "src/favicon.ico",
              "src/app/forms"
            ], 

然后您的服务方法将如下所示;

getPersonalInformation(): Observable<Person> {
    return this.http.get<Person>('./assets/person.json');
  }

随后将调用该服务;

this.personListService.getPersonalInformation()
    .subscribe(
      (data: Person) => {
        this.persons = data;
        console.log(JSON.stringify(this.person));  }, /*added this to display the object in console*/
      (error: any ) => console.log(error)
    );

在您的HTML文件中,您只需使用{{persons.FirstName}},就不需要“ this”。

我注意到person.json与类型Person不匹配,您应该尝试避免这种情况。

希望这会有所帮助。