【问题标题】:How in the angular output information obtained through the "get"?如何在通过“get”获得的角度输出信息?
【发布时间】:2017-12-22 08:19:55
【问题描述】:

如何将接收到的数据写入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);
}

【问题讨论】:

  • “记录”是什么意思?
  • @Flaugzig 写
  • setTimeout 按设计执行一次。另请参阅this 页面。
  • 我还是不明白你的问题。是否要从响应中提取数据?
  • @Flaugzig 我想知道如何获取数据并将其写入正确的变量。如果问了一个不清楚的问题,我很抱歉

标签: javascript angular promise angular-promise angular-http


【解决方案1】:

试试这个:-

为来自@angular/http的响应添加导入

this.http.get('http://localhost:1337/api/users') 
      .toPromise() 
      .then((response:Response)=> { this.tmp = response.json() }) 
      .catch(this.handleError);

您编写setTimeout()ngOnInit() 生命周期钩子将在构造函数之后仅执行一次。如果编写的代码在组件中,那么它将在每次创建组件对象时执行,但如果它在服务中,那么它将在您提供服务时执行一次,因为服务对象是单例对象

【讨论】:

  • 感谢this.http.get。 setTimeout 在另一个函数中也不起作用。
  • 你能告诉我你在哪里添加 setTimeout()
  • 这与setTimeout() 无关。这是关于你在哪里使用它。如果您允许我出于您想要的目的使用setTimeout(),那么我可能会为您提供帮助。
  • 函数GetUsers
  • 抱歉,我无法联系到您。你能修改你的代码吗?
猜你喜欢
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
相关资源
最近更新 更多