在ES5中使用Angular2最终版本2.0.1的http获取示例

时间:2016-09-26 18:08:54

标签: angular angular-services

由于不推荐使用ng.http.HTTP_PROVIDERS来支持ng.http.HttpModule,我无法在我的组件中使用HTTP GET请求。

这是组件:

(function (app) {
app.ServiceComponent = ng.core
    .Component({
        selector: 'service',
        templateUrl: 'app/service/service.component.html',
        directives: [ ng.router.ROUTER_DIRECTIVES, app.NestedComponent ],
        providers: [app.TestService, ng.http.HttpModule ]
    })
    .Class({
        constructor: [app.TestService, function(testService) {
            this.title = 'Service Page Test';
            this.body =  'Service Body Test';
            this.message = '';
            this.xhr = {};
            this.testService = testService;
        }],
        ngOnInit: function() {
            this.message = this.testService.getMessage();
            this.xhr = this.testService.getData();
        }
    });
})(window.app || (window.app = {}));

这是服务:

(function(app) {

app.TestService = function (http) {
    this.message = 'Hello Message Test';
    this.url = "service.json";
    this.http = http;
};


app.TestService.parameters = [ ng.http.Http ];

app.TestService.prototype.getMessage = function () {
    return this.message;
};

app.TestService.prototype.setMessage = function (newMessage) {
    this.message = newMessage;
};

app.TestService.prototype.getData = function () {
    return this.http.get(this.url)
        .map(function (response) {
            return response.json().data;
        })
        .catch();
   };})(window.app || (window.app = {}));

我收到错误:

core.umd.js:3433 Error: Uncaught (in promise): TypeError: Cannot read property '__platform_browser_private__' of undefined
at resolvePromise (zone@0.6.23.js:418)

1 个答案:

答案 0 :(得分:2)

您必须在html中以正确的顺序包含angular2脚本:

<script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.6.21/dist/zone.min.js"></script>
<script src="https://unpkg.com/rxjs@5.0.0-beta.12/bundles/Rx.min.js"></script>

<script src="https://unpkg.com/@angular/core@2.0.1/bundles/core.umd.js"></script>
<script src="https://unpkg.com/@angular/common@2.0.1/bundles/common.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser@2.0.1/bundles/platform-browser.umd.js"></script>
<script src="https://unpkg.com/@angular/compiler@2.0.1/bundles/compiler.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser-dynamic@2.0.1/bundles/platform-browser-dynamic.umd.js"></script>
<script src="https://unpkg.com/@angular/http@2.0.1/bundles/http.umd.js"></script>

<强> Plunker Example Http request in ES5