javascript - 如何在 Angular 输出中通过 "get"获得信息?

标签 javascript angular promise angular-promise angular-http

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

相关文章:

javascript - 如何避免使用 trackBy 函数避免为 nGFor 重建 DOM - Angular Firestore

angular - fakeAsync 不等待异步操作完成

javascript - 我得到 Promise { <pending> } 作为返回值,并且在异步作用域中调用也会立即给我未定义的结果

promise - Promise 对象内外的分号

javascript - 我如何(有效地)链接我的 promise ,返回一个有值(value)的数组而不是 promise ?

javascript - 如何使用 Factory 在 mouseleave 上关闭 Angular-ui-bootstrap uibModal?

javascript - 仅在移动屏幕尺寸上使用 slick.js

asp.net - No NgModule metadata found for 'AppModule' Error in Angular 5 server-side rendering with --env.prod

javascript - 使用 sinon.fakeServer 获取夹具数据

javascript - 如果启动后互联网可用,如何使用预加载器加载外部 JavaScript?