我正在尝试访问数组countriesList,它是我在Angular 4组件中收到的响应。响应包含有关国家的详细信息,如名称、首都、人口等。
如何在我的component.ts中获得数组countriesList的长度?
import { Component, OnInit } from '@angular/core';
import { Chart, Highcharts } from 'angular-highcharts';
import { CountriesserviceService } from '../countriesservice.service';
@Component({
selector: 'app-graph1',
templateUrl: './graph1.component.html',
styleUrls: ['./graph1.component.css'],
providers: [CountriesserviceService]
})
export class Graph1Component implements OnInit {
countriesList: any[];
constructor(private countriesService: CountriesserviceService) { }
ngOnInit() {
this.countriesService.getCountries().subscribe(countriesList =>
this.countriesList = countriesList.json() );
console.log(this.countriesList);
}
}发布于 2017-11-09 20:43:02
尝试这样做:
ngOnInit() {
this.countriesService.getCountries().subscribe(
(res) => this.onSuccess(res.json, res.headers),
(res) => this.onError(res.json)
);
}
private onSuccess(data, headers) {
this.countriesList = data;
}
private onError(error) {
console.log(error.toString());
}发布于 2017-11-09 20:44:16
要获取数组长度,可以使用第二种方法:
ngOnInit() {
this.countriesService.getCountries()
.map( res => res.json())
.subscribe(countries => {
this.countriesList = countries
console.log(this.countriesList.length)
})
}注意,它是异步代码,所以console.log必须在subscribe中。如果它在外部,则显示默认值(O,null,[],undifined,...)
- post编辑前-
有两种方法可以显示getCountries的结果
优先:
您可以将可观察到的getCountries直接影响组件的属性:
ngOnInit() {
this.countriesList$ = this.countriesService.getCountries().map( res => res.json())
}并使用异步管道进入HTML angular组件:
<ul>
<li *ngFor="let country of countriesList$ | async">{{country.name}}</li>
</ul>我在属性名的末尾使用$,因为在typescript/rxjs中为stream (observable)的名称添加$是一种惯例
Second:
您可以通过HTML组件的属性来影响observable的结果:
ngOnInit() {
this.countriesService.getCountries()
.map( res => res.json())
.subscribe(countries => this.countriesList = countries)
}在组件中:
<ul>
<li *ngFor="let country of countriesList">{{country.name}}</li>
</ul>我的例子很简单,这取决于你的getCountries方法做了什么
发布于 2017-11-09 21:22:26
试着这样做:
export class Graph1Component implements OnInit {
countriesList: Array<any> = [];
constructor(private countriesService: CountriesserviceService) { }
ngOnInit() {
this.countriesService.getCountries().subscribe(countriesList => {
this.countriesList = countriesList.json();
console.log("countries length", this.countriesList, this.countriesList.length);
});
}
}https://stackoverflow.com/questions/47202009
复制相似问题