如何使用Http类在Angular 2中获取json文件?

时间:2015-09-29 17:49:50

标签: typescript angular

我正在尝试使用Angular 2中的Http类获取一个json文件。我按照Angular 2主页上的示例进行了操作:https://angular.io/docs/js/latest/api/http/Http-class.html。 但是,我收到以下错误消息。我使用的是Angular 2.0.0-alpha.37,traceur 0.0.91,systemjs 0.16.11,es6-module-loader 0.16.6和typescript 1.6.2。关于这里可能出现什么问题的任何想法?

app.ts

///<reference path="typings/angular2/angular2.d.ts"/>
///<reference path="typings/angular2/http.d.ts"/>
import {Component, View, bootstrap} from 'angular2/angular2';
import {Http, HTTP_BINDINGS} from 'angular2/http';

@Component({
  selector: 'myApp',
  viewBindings: [HTTP_BINDINGS]
})
@View({
  templateUrl: 'myapp.html'
})
class MyComponent {
  data: Object;
  constructor(http: Http) {
    http.get('data.json').toRx().map(res => res.json()).subscribe(data => this.data = data);
  }
}
bootstrap(MyComponent);

的index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="../node_modules/angular2/bundles/http.dev.js"></script>
    <script src="../node_modules/traceur/bin/traceur-runtime.js"></script>
    <script src="../node_modules/es6-module-loader/dist/es6-module-loader.js"></script>
    <script src="../node_modules/systemjs/dist/system.src.js"></script>
  </head>
  <body>
    <myApp></myApp>
    <script>
      System.import('app');
    </script>
  </body>
</html>

结果

EXCEPTION: Error during instantiation of MyComponent!.
EXCEPTION: Error during instantiation of MyComponent!.
ORIGINAL EXCEPTION: TypeError: Rx.Subject is not a function
ORIGINAL STACKTRACE:
TypeError: Rx.Subject is not a function
    at new EventEmitter (angular2.dev.js:22672)
    at new XHRConnection (http.dev.js:7474)
    at XHRBackend.createConnection (http.dev.js:7519)
    at httpRequest (http.dev.js:7291)
    at Http.get (http.dev.js:7369)
    at new MyComponent (:8080/src/app.js:19)
    at angular2.dev.js:8937
    at Injector._proto._instantiate (angular2.dev.js:28045)
    at Injector._proto._new (angular2.dev.js:27985)
    at InjectorInlineStrategy.protoStrategy.instantiateBinding (angular2.dev.js:27774)
ERROR CONTEXT:
_Context
EXCEPTION: TypeError: Cannot read property 'location' of undefined
EXCEPTION: TypeError: Cannot read property 'location' of undefined
STACKTRACE:
TypeError: Cannot read property 'location' of undefined
    at angular2.dev.js:27298
    at Zone.run (angular2.dev.js:136)
    at Zone.run (angular2.dev.js:16593)
    at zoneBoundFn (angular2.dev.js:109)
    at lib$es6$promise$$internal$$tryCatch (angular2.dev.js:1419)
    at lib$es6$promise$$internal$$invokeCallback (angular2.dev.js:1431)
    at lib$es6$promise$$internal$$publish (angular2.dev.js:1402)
    at angular2.dev.js:187
    at microtask (angular2.dev.js:16619)
    at Zone.run (angular2.dev.js:136)
EXCEPTION: TypeError: Cannot read property 'hostView' of undefined
EXCEPTION: TypeError: Cannot read property 'hostView' of undefined
STACKTRACE:
TypeError: Cannot read property 'hostView' of undefined
    at zone.run.tick (angular2.dev.js:27331)
    at Zone.run (angular2.dev.js:136)
    at Zone.run (angular2.dev.js:16593)
    at zoneBoundFn (angular2.dev.js:109)
    at lib$es6$promise$$internal$$tryCatch (angular2.dev.js:1419)
    at lib$es6$promise$$internal$$invokeCallback (angular2.dev.js:1431)
    at lib$es6$promise$$internal$$publish (angular2.dev.js:1402)
    at angular2.dev.js:187
    at microtask (angular2.dev.js:16619)
    at Zone.run (angular2.dev.js:136)

3 个答案:

答案 0 :(得分:8)

更新为angular2 Beta

至于Angular2现在处于测试阶段,所以我觉得根据angular2 beta的一些变化来回答这个问题。   所以这里是必须遵循的一些变化的清单:

  1. 进口angular2
  2. 这个

    import {Component, View, bootstrap} from 'angular2/angular2';
    import {Http, HTTP_BINDINGS} from 'angular2/http';
    

    应更改为:

    import {Component, View} from 'angular2/core';
    import {Http, HTTP_PROVIDERS} from 'angular2/http';
    import {bootstrap} from 'angular2/platform/browser';
    

    有关进口的更多信息,请参见此处   所有进口商品清单,以角度为单位,自beta。

    Cannot find module 'angular2/angular2'

    1. viewBindings:[HTTP_BINDINGS]: - HTTP_BINDINGS已更改为HTTP_PROVIDERS。 如果我们在引导我们的app.like这个

      时提供所有基本绑定会更好

      自举(MyComponent的,[HTTP_PROVIDERS]);

    2. @View本身提供的所有功能都无需提供额外的@Component注释。忽略这一点:

    3. @View({
          templateUrl: 'myapp.html'
        })
      

      使用它:

        @Component({
          selector: 'myApp',
          templateUrl: 'myapp.html'
        })
      
      1. 使用HTTP获取JSON文件。

        首先,我们都知道Angular2是投射可观察对象而不是角度1.x中的承诺。所以为了处理Observable Object,我们需要RxJs个方法,.map and .subscribe.map方法接受Observable对象并转换为我们想要的形式,如text(),Json(),根据需要在这里读出https://angular.io/docs/js/latest/api/http/Response-class.html
      2.   class MyComponent {
          data: Object;
            constructor(private http: Http) {
              http.get('data.json')
                .map(res => res.json())
                .subscribe(data => this.data = data,
                            err => console.log(err),
                            () => console.log('Completed'));
            }
          }
        

        有关Angular2中有关HTTP服务的更多信息,请阅读这些答案。

答案 1 :(得分:0)

您需要引导[HTTP_BINDINGS]

更改此行:

bootstrap(MyComponent);

到此:

bootstrap(MyComponent,[HTTP_BINDINGS]);

答案 2 :(得分:0)

如果你想在角度2中使用http get方法读取.json文件,它依赖于你使用构建工具。

如果您使用angular-cli,那么您需要将.json文件放在assets文件夹中并尝试读取该文件,如

http.get('<your file path inside assets folder>.json')

但是如果您使用webpack,那么您需要将相同的.json文件放在公共文件夹

http.get('<your file path inside assets folder>.json')

它会起作用