【问题标题】:HTTP GET request with AngularJS 2 and ES6AngularJS 2 和 ES6 的 HTTP GET 请求
【发布时间】:2016-03-01 13:47:56
【问题描述】:

如何使用 JavaScript (ES6) 在 AngularJS 2 中执行 HTTP GET 请求?该文档仅使用 TypeScript 显示。

【问题讨论】:

    标签: javascript angularjs angular http-get


    【解决方案1】:

    你可以使用类似的东西:

    import {Http, URLSearchParams} from 'angular2/http';
    
    @Injectable()
    export class SomeHttpService {
      constructor(http) {
        this.http = http;
      }
    
      getSomething() {
        URLSearchParams params = new URLSearchParams();
        params.set('id', '1');
        return this.http.get('http://...', { search: params }).map(res => res.map());
    
        /*
          or if you need to subscribe in the service
    
          this.http.get('http://...').map(res => res.map())
                   .subscribe(
                     (data) => {
                       // do something with data
                     }
                   );
        */
      }
    
      static get parameters() {
        return [[Http]];
      }
    }
    

    别忘了导入Angular2 Http模块文件:

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/http.dev.js"></script> <---
    

    并在引导您的应用程序时设置 HTTP_PROVIDERS 提供程序:

    import {HTTP_PROVIDERS} from 'angular2/http';
    (...)
    
    bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
    

    事实上,ES6 唯一特有的就是使用静态 getter 配置依赖注入的方式...

    【讨论】:

    • 我如何传递参数,例如 'id=1'
    • 使用URLSearchParams,但这不是 ES6 特有的...我更新了我的答案
    • 感谢我们的帮助,我会处理并发布结果
    • 什么是 HTTP_PROVIDERS?
    • HTTP_PROVIDERS 包含使用 HTTP 的提供者列表。它包含HttpHttp 类所依赖的其他。您需要定义它们以便能够在您的服务或组件中注入 Http 实例。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多