【问题标题】:When Using Typescript+angularjs the api result is not displaying in html使用 Typescript+angularjs 时,api 结果未在 html 中显示
【发布时间】:2015-10-11 17:10:56
【问题描述】:

下面是我的控制器和 html:当我在控制器中调用 make api 时,我将结果存储在结果变量中,现在,当我尝试在 html 中打印时,结果变量没有打印任何内容,我已经使用了另一个当我打印它时,控制器中的变量名在 html 中打印。但是当我尝试在控制器中打印结果变量时,它正在控制台中打印数据。所以,我正确地获取了变量中的数据。但是,为什么它不在 html 中打印。请帮忙。

控制器:

module typescript {

    var my_app = angular.module('my_app', []);
    export class test {

        public name: any;
        constructor(private $http: ng.IHttpService) {
            this.name = "Test data";
            this.getdata();
        }

        getdata() {
            return this.$http.get('facilities.json').success(function(response) {
                this.result = response;
                console.log(this.result);
            })
        }
    }
    test.$inject = ['$http'];
    myapp.controller("test", test);
}

任何帮助将不胜感激。

【问题讨论】:

  • {{test1.result}}
    {{test1 .name}}
  • 使用 Typescript 你可以使用'static $inject = ['$http'];'在你的班级内,而不是用它来扩展班级。把它放在构造函数的正上方。

标签: angularjs typescript


【解决方案1】:

您必须小心this 语义。在这段代码中:

return this.$http.get('facilities.json').success(function(response) {
   this.result = response;
   console.log(this.result);
})

this 不是指您的 test 实例,而是指函数正在运行的任何上下文。而是这样做:

return this.$http.get('facilities.json').success(response => {
   this.result = response;
   console.log(this.result);
})

现在这指向test 实例。 Read this 了解更多关于 this 新用途的信息。不过,您仍然必须在某处定义 result 属性:)

祝你好运。

【讨论】:

  • 谢谢@mrhobo。当我使用箭头函数时,它起作用了:-)。但是,你能告诉我如何在对被调用者的 api 调用之后返回结果属性,即类似于 storeresult = this.获取数据();。现在 storeresult 变量应该有 api 结果。因为,箭头函数在 IE8 中不支持。在此先感谢
  • ie 8 支持箭头函数,因为 typescript 将箭头函数转换为常规函数。由于您的 api 调用是异步的,因此您需要 promise。
  • 谢谢@Lodewijk。我只想获取api结果并希望返回结果。那么我如何在从 api 获得响应后将结果传递给被调用者。使用上面的代码,如果我通过 return this.result 它什么也不返回。你能帮我吗?。
  • @mahi244 test.getdata()正在返回一个承诺,该承诺将解析来自 API 的响应。您不能同步访问,只能异步访问。如果你还没有遇到 Promise,我强烈建议你单独阅读它们,然后再回到这个问题。一旦你这样做了,你应该更清楚地了解发生了什么。
猜你喜欢
  • 2016-03-03
  • 2017-06-09
  • 2013-12-22
  • 2021-12-08
  • 2021-01-25
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多