我尝试使用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>
答案 0 :(得分:1)
您应该使用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
部分: