无法在 typescript angular 8 中使用 any = {} 获取值
cannot able to get values using any = {} in typescript angular8
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
enableProdMode();
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
values: any = {};
constructor(private http: HttpClient) { }
ngOnInit() {
this.getValues();
console.log(this.values);
}
getValues()
{
this.http.get('http://localhost:5000/api/values').subscribe(Response => { this.values = Response},error => {console.log(error);
});
}
}
我可以从 HTTP 获取值 response.but 我无法将这些值存储在 'values' 对象中。得到空数组。
您需要将 console.log 放在订阅中,因为在您的 console.log 执行时它被异步调用,所以没有结果。
getValues()
{
this.http.get('http://localhost:5000/api/values').subscribe(Response => {
this.values = Response;
console.log("##Got values", this.values);
},error => {console.log(error);
});
}
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
enableProdMode();
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
values: any = {};
constructor(private http: HttpClient) { }
ngOnInit() {
this.getValues();
console.log(this.values);
}
getValues()
{
this.http.get('http://localhost:5000/api/values').subscribe(Response => { this.values = Response},error => {console.log(error);
});
}
}
我可以从 HTTP 获取值 response.but 我无法将这些值存储在 'values' 对象中。得到空数组。
您需要将 console.log 放在订阅中,因为在您的 console.log 执行时它被异步调用,所以没有结果。
getValues()
{
this.http.get('http://localhost:5000/api/values').subscribe(Response => {
this.values = Response;
console.log("##Got values", this.values);
},error => {console.log(error);
});
}