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

时间:2019-04-08 07:17:45

标签: html typescript angular5 angular-httpclient

我尝试使用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>

1 个答案:

答案 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部分:

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