如何在浏览器控制台上显示从服务器获取的值?

问题描述 投票:0回答:1

我尝试使用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>
html typescript angular5 angular-httpclient
1个回答
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部分:

https://angular.io/tutorial/toh-pt6

© www.soinside.com 2019 - 2024. All rights reserved.