【问题标题】:Angular 2: How to use Http in ES5?Angular 2:如何在 ES5 中使用 Http?
【发布时间】:2015-11-01 01:54:06
【问题描述】:

目前,我正在使用 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);
});

谁能帮我解决这个问题?谢谢。

【问题讨论】:

  • 需要更多信息。您遇到什么错误?
  • 很抱歉缺少信息。我收到“..Http 未定义”错误。
  • 是否定义了“ng”?你能看看 Http 对象是不是 ng 的一部分吗?
  • 我在ng里面没有看到任何Http对象,那么如何定义Http呢?它在另一个模块上吗?我只使用code.angularjs.org/2.0.0-alpha.44/angular2.sfx.dev.js 模块(Plunker 中默认的 Angular 2 ES5)。

标签: angular


【解决方案1】:

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

这是我的代码:

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);
});

原来,Http对象在ngHttp中。我认为由于 Angular 2 目前仍处于 Alpha 版本且变化迅速,因此缺乏文档。我希望这能帮助那些和我有同样问题的人。

【讨论】:

  • 这是我发现的在 ES5 中使用 ngHttp 的最佳示例。谢谢!
  • 你包含什么文件来实现这个?根据我包含的文件,我得到 ngHttp 未定义或系统未定义或 require 未定义。我就是无法让它工作。
  • 这里一样,ngHttp 未定义... app.module.js 中应该放什么?
【解决方案2】:

对于 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 = {}));

【讨论】:

  • 这会导致错误:只允许 Provider 和 Type 的实例
【解决方案3】:

为了让它与 beta 版本一起工作,我必须将 ngHttp 更改为 ng.http

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多