我尝试使用angular中的httpclient get方法从服务器检索值。但我无法在控制台或网页上查看它。我怎么做?
打字稿文件:
export class CountryComponent implements OnInit {
constructor(private http:HttpClient) { }
country:Observable<Country[]>;
ngOnInit() {
this.country=this.http.get<Country[]>(path+"/getAllCountries");
console.log(this.country);
}
}
HTML:
<ul>
<li *ngFor="let count of country">
{{(count.id}}
</li>
</ul>
你应该使用async
管道或subscribe
来http请求。
第一种方式async
。让Angular处理订阅本身
<li *ngFor="let count of country | async">
{{(count.id}}
</li>
第二种方式subscribe
:
export class CountryComponent implements OnInit {
constructor(private http:HttpClient) { }
country:Observable<Country[]> = [];
ngOnInit() {
this.http.get<Country[]>(path+"/getAllCountries").subscribe(response => {
this.country = response;
console.log(this.country);
})
}
你可以看看官方教程Http
部分: