如何将接收到的数据写入tmp
?通过return
,从函数中返回promise
对象,而在函数tmp
中它是不可见的
tmp: string;
constructor(private http: Http) {
this.tmp = "load";
this.GetUsers();
}
ngOnInit() {
setTimeout(console.log("Hello"), 2000);
}
GetUsers() {
this.http.get('http://localhost:1337/api/users')
.toPromise()
.then(function(response) {
this.tmp = "success"
})
.catch(this.handleError);
此外,setTimeout
不起作用。也就是说,它只能一次有效。
constructor(private http: Http) {
this.tmp = "load";
this.GetUsers();
}
ngOnInit() {
}
GetUsers() {
setTimeout(console.log("Hello"), 2000);
}
最佳答案
试试这个:-
添加来自 @angular/http
的响应导入
this.http.get('http://localhost:1337/api/users')
.toPromise()
.then((response:Response)=> { this.tmp = response.json() })
.catch(this.handleError);
您编写了 setTimeout()
的 ngOnInit()
生命周期 Hook 将仅在构造函数之后执行一次。如果编写的代码在组件中,那么每次创建组件对象时都会执行一次,但如果在服务中,那么当您提供服务时,它就会执行一次,因为服务对象是单例对象
关于javascript - 如何在 Angular 输出中通过 "get"获得信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45150272/