Angular 2:如何在ES5中使用Http?

asu*_*sky 1 angular

目前,我正在玩Angular 2.我尝试在ES5中使用Http,但无法使其正常工作.错误说"Http未定义".

这是我的代码:

function Service() {}
Service.prototype.greeting = function() {
  return 'Hello';
};

var Cmp = ng.
  Component({
    selector: 'cmp',
    providers: [Service],
    directives: [ng.NgFor],
    injectors: [ng.Http, ng.HTTP_PROVIDERS],
    templateUrl: 'hello.html'
  }).
  Class({
    constructor: [Service, function Cmp(service) {
      this.greeting = service.greeting();
      ng.Http.get('people.json');
    }],
  });

document.addEventListener('DOMContentLoaded', function() {
  ng.bootstrap(Cmp);
});
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题吗?谢谢.

asu*_*sky 8

我终于设法解决了自己的问题.

这是我的代码:

function Service() {}
Service.prototype.greeting = function() {
  return 'Hello';
};

var Cmp = ng.
  Component({
    selector: 'cmp',
    providers: [Service, ngHttp.HTTP_PROVIDERS],
    template: '{{greeting}}, {{result.name}}!'
  }).
  Class({
    constructor: [Service, ngHttp.Http, function Cmp(service, Http) {
      this.greeting = service.greeting();
      this.result = {};
      this.http = Http;
      this.mapPeople().subscribe(function(result){
        this.result = result;
      }.bind(this));
    }],
    mapPeople: function(){
      return this.http.get('people.json').map(function (res) {
              return res.json();
          });
    }
  });

document.addEventListener('DOMContentLoaded', function() {
  ng.bootstrap(Cmp);
});
Run Code Online (Sandbox Code Playgroud)

结果是,Http对象在ngHttp中.我认为,由于Angular 2目前仍处于Alpha版本并且发生了迅速变化,因此缺乏文档.我希望这能帮助那些遇到与我一样的问题的人.

  • 你包含什么文件来实现这个目标?我得到ngHttp未定义或未定义System或未根据我包含的文件定义require.我只是无法让这个工作. (3认同)

小智 6

对于Angular 2 Beta版,它的工作方式如下

(function(app) {

app.MyName = ng.core
  .Component({
    selector: 'my-name',
    template: '<span>Dave</span>',
    providers: [ng.http.HTTP_PROVIDERS]
  })
  .Class({
    constructor: [ng.http.Http, function(http) {

    }]
  });

app.HelloApp =
  ng.core.Component({
    selector: 'hello-app',
    template: '<h1>Hello Angular 2!</h1><my-name></my-name>',
    directives: [app.MyName]
  })
  .Class({
    constructor: function(){}
  });
})(window.app || (window.app = {}));
Run Code Online (Sandbox Code Playgroud)