从 json 中获取 p-dropdown 的数据
2018-12-06
1560
我正在使用 p-dropdown 显示国家列表并选择国家。所以我在 data.length 处收到错误,说运算符 '<' 不能应用于类型 'number' 和 'Observable'。我不知道如何解决这个错误。我是 angular 新手。请给出解决方案。
Countries:SelectItem[];
this.Countries.push({ label: 'Select Item', value: -1});
var data = this.http.get('app/form/country.json')
for(let i = 0; i< data.length; i++) {
this.Countries.push({label: data[i].Country, value: data[i].Name});
}
contact.component.ts
import { Component, OnInit } from '@angular/core';
import { SelectItem } from 'primeng/api';
import { CountryService } from './country-list.service';
import { StateService } from './state-list.service';
import { CityService } from './city-list.service';
import { Message } from 'primeng/components/common/api';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { PersonListService,Address, Email, ContactNumber} from './person-list.service';
import { HttpClient } from '@angular/common/http';
@Component({
moduleId: module.id,
selector: 'sd-contactform',
templateUrl: 'contactform.component.html',
styleUrls: ['contactform.component.css']
})
export class ContactFormComponent implements OnInit {
addresses: Address[];
addresstype: Array<String>=[''];
states:Array<String>=[''];
countries:Array<String>=[''];
errorMessage: any;
Countries:SelectItem[];
Country:string;
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:Array<String>=[''];
contacttype:Array<String>=[''];
ContactTypes: SelectItem[];
country: any;
filteredCountriesSingle: any[];
filteredStatesSingle: any[];
city: any;
filteredCitiesSingle: any[];
msgs: Message[] = [];
address: FormGroup;
email: FormGroup;
contact: FormGroup;
submitted: boolean;
i:number;
data: any;
constructor(public personListService:PersonListService,private countryService: CountryService,private http: HttpClient,private stateService: StateService,private cityService: CityService,private fb: FormBuilder) { }
filterCountrySingle(event) {
let query = event.query;
this.countryService.getCountries().then(countries => {
this.filteredCountriesSingle = this.filterCountry(query, countries);
});
}
filterCountry(query, countries: any[]):any[] {
let filtered : any[] = [];
for(let i = 0; i < countries.length; i++) {
let country = countries[i];
if(country.country.toLowerCase().indexOf(query.toLowerCase()) == 0) {
filtered.push(country);
}
}
return filtered;
}
filterStateSingle(event) {
let query = event.query;
this.stateService.getStates().then(states => {
this.filteredStatesSingle = this.filterState(query,states);
});
}
filterState(query,states: any[]):any[] {
let filtered : any[] = [];
for(let i = 0; i < states.length; i++) {
let state = states[i];
if(state.state.toLowerCase().indexOf(query.toLowerCase()) == 0) {
console.log(state)
console.log(filtered)
filtered.push(state);
}
}
return filtered;
}
filterCitySingle(event) {
let query = event.query;
this.cityService.getCitys().then(cities => {
this.filteredCitiesSingle = this.filterCity(query,cities);
});
}
filterCity(query,cities: any[]):any[] {
let filtered : any[] = [];
for(let i = 0; i < cities.length; i++) {
let city = cities[i];
if(city.city.toLowerCase().indexOf(query.toLowerCase()) == 0) {
console.log(city);
filtered.push(city);
}
}
return filtered;
}
ngOnInit() {
this.getperson();
this.address = this.fb.group({
'addresstype': new FormControl('', Validators.required),
'addressl1': new FormControl('', Validators.required),
'addressl2': new FormControl('', Validators.required),
'state1': new FormControl('', Validators.required),
'locality': new FormControl('', Validators.required),
'city': new FormControl('', Validators.required),
'country': new FormControl('', Validators.required),
'postalcode': new FormControl('', Validators.required)
}
);
this.email = this.fb.group({
'emailtype': new FormControl('', Validators.required),
'emailid': new FormControl('', [Validators.required,
Validators.pattern("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$")] )
}
);
this.contact = this.fb.group({
'contacttype': new FormControl('', Validators.required),
'countrycode': new FormControl('', Validators.required),
'regioncode': new FormControl('', Validators.required),
'mobileno': new FormControl('', [Validators.required,Validators.minLength(10),Validators.maxLength(10)])
}
);
this.AddressTypes = [
{label: 'Native', value: 'Native'},
{label: 'Temporary', value: 'Temporary'},
{label: 'Permanent', value: 'Permanent'},
{label: 'Careof', value: 'Careof'}
];
this.EmailTypes = [
{label: 'Personal', value: 'Personal'},
{label: 'Office', value: 'Office'}
];
this.ContactTypes = [
{label: 'Home', value: 'Home'},
{label: 'Office', value: 'Office'}
];
var data = [];
this.Countries=[];
this.Countries.push({ label: 'Select Item', value: -1})
this.http.get('app/form/country.json')
.subscribe(data => this.data = data, // success path
error => this.errorMessage = error // error path
);
for(let i = 0; i<this.data.length ; i++) {
//the property after data[i]. needs to match the exact name that is on your JSON file... So, name is a different property than Name
this.Countries.push({label: this.data[i].country, value: this.data[i].Value});
console.log(this.data[i].Value)
}
}
onSubmit(value: string) {
this.submitted = true;
this.msgs = [];
this.msgs.push({severity:'info', summary:'Success', detail:'Form Submitted'});
}
getperson(){
this.personListService.getAddress()
.subscribe(
resp => {
this.addresses = resp.Addresses
var i;
for(i=0;i<this.addresses.length;i++)
{
this.states[i]=this.addresses[i].State
//this.countries[i]=this.addresses[i].Country
this.addresstype[i]=this.addresses[i].AddressType
}
console.log(this.addresstype)
console.log(this.states)
console.log(this.countries)
console.log(this.addresses)
});
this.personListService.getEmail()
.subscribe(
resp =>{
this.emails = resp.Emails
var i;
for(i=0;i<this.emails.length;i++)
{
this.emailtype[i]=this.emails[i].EmailType
}
console.log(this.emails.length)
}
);
this.personListService.getContact()
.subscribe(
resp => {
this.contactnumbers = resp.ContactNumbers
var i;
for(i=0;i<this.contactnumbers.length;i++)
{
this.contacttype[i]=this.contactnumbers[i].ContactType
}
//resp => this.addresses = resp.Addresses,
error => this.errorMessage = <any>error
}
);
}
}
我添加了 compnent.ts 文件的代码。请检查,我收到错误为 ERROR TypeError: Cannot read property 'length' of undefined at data.length 所以请告诉我出了什么问题?
2个回答
Because the service method returns an Observable of configuration data, the component subscribes to the method's return value. The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display. Read more: httpClient
Countries:SelectItem[];
var data = [];
this.Countries.push({ label: 'Select Item', value: -1});
this.http.get('app/form/country.json').subscribe(data => this.data = data);
for(let i = 0; i< data.length; i++) {
this.Countries.push({label: data[i].Country, value: data[i].Name});
}
您正在将可观察对象分配给
data
。要获取值,您需要订阅值。检查错误可能对您很重要:
this.http.get('app/form/country.json')
.subscribe(data => this.data = data, // success path
error => this.error = error // error path
);
Maihan Nijat
2018-12-06
订阅请求
Countries:SelectItem[];
this.Countries.push({ label: 'Select Item', value: -1});
this.http.get('app/form/country.json').subscribe((data)=>{
for(let i = 0; i< data.length; i++) {
this.Countries.push({label: data[i].Country, value: data[i].Name});
}
})
Nastya Scherbakova
2018-12-06