我正在使用p下拉列表显示国家列表并选择国家。所以我在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文件的代码。请检查,我得到的错误为错误TypeError:无法读取data.length中未定义的属性“ length”,因此请告诉我什么地方出错了?
答案 0 :(得分:1)
订阅请求
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});
}
})
答案 1 :(得分:1)
因为服务方法返回一个Observable配置 数据,则该组件订阅该方法的返回值。的 订阅回调将数据字段复制到组件的 config对象,在组件模板的数据绑定中 显示。 了解更多: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
);