我正在尝试从JSON编码的PHP脚本API访问数据,如下所示:
export class AppComponent {
test = 'Angular is live';
private data;
constructor(private http:Http) {}
ngOnInit() {
this.getData();
}
getData() {
console.log('-- GETTING DATA --');
// DATA GRABBING PATTERN
this.
http.
get('https://localhost:3000/sampleData.php').
subscribe(
function(response) {
res => this.data = res.json()
},
function(error) {
console.log('error grabbing the data');
},
function() { // COMPLETE
console.log('grabbing data is complete');
console.log(this.data); // WHY IS THIS RETURNING UNDEFINED?
}
);
console.log(this.data);
}
}
我输出的所有地方console.log(this.data)
我都是未定义的,但是当我访问模板中的变量{{data}}
时,它输出数据就好了。
我怎么知道observable何时完成抓取数据?或者我在想这个错误?
这是sampleData.php文件:
<?php
header("Access-Control-Allow-Origin: *");
$data = array(
array('id' => '1','first_name' => 'Cynthia'),
array('id' => '2','first_name' => 'Keith'),
array('id' => '3','first_name' => 'Robert'),
array('id' => '4','first_name' => 'Theresa'),
array('id' => '5','first_name' => 'Margaret')
);
echo json_encode($data);
?>
答案 0 :(得分:3)
您需要使用arrow functions
代替函数来保存this
属性。
subscribe(
(res) => { this.data = res.json() } ,
(error) => {
console.log('error grabbing the data');
},
()=> { // COMPLETE
console.log('grabbing data is complete');
console.log(this.data); // WHY IS THIS RETURNING UNDEFINED?
}
);
答案 1 :(得分:2)
使用arrow functions使this
指向当前的类实例
subscribe(
response => this.data = response.json(),
error => {
console.log('error grabbing the data');
},
() => {
console.log('grabbing data is complete');
console.log(this.data); // WHY IS THIS RETURNING UNDEFINED?
}
只有在您需要使用this
时才需要它,但它可以在任何地方使用,并且如果您始终如一地使用它,则不易出错。