【问题标题】:How to call a simple http GET service in Angular 2如何在 Angular 2 中调用简单的 http GET 服务
【发布时间】:2016-12-12 11:11:33
【问题描述】:

我正在学习 Angular 2,我试图在页面加载时为我拥有的 JSON 数据调用一个简单的 HTTP Get 请求,并在页面加载时操作该 JSON。谁能告诉我一些基本的例子如何做到这一点?我在网上看到的大多数解决方案都是 Beta 版。

【问题讨论】:

    标签: angular angular2-http


    【解决方案1】:

    要获取 observable,您可以按照以下示例进行操作。 getStories 方法使用注入的 HTTP 服务,并返回一个 observable,可进一步用于获取响应。

    @Injectable()
    export class StoriesService {
    
        constructor(private http:Http,private constService :ConstantsService) { }
    
        public getStories()
        {
            this.http
                .get(this.constService.apiBaseUrl + "Stories/Stories")
                .subscribe ((data: Response) => console.log(data));
        }
    }
    

    这是一个简单的 HTTP 获取服务示例。

    【讨论】:

      【解决方案2】:

      创建如下服务:

      import { Injectable } from '@angular/core';
      import { Http, Response } from '@angular/http';
      import 'rxjs/Rx';
      import {Observable} from 'rxjs/Rx'
      
      export class MyService {
        constructor(public http: Http) { }
      
        private extractData(res) {
      
          if (res.status < 200 || res.status >= 300) {
            throw new Error('Bad response status: ' + res.status);
          }
      
          // console.log(res.json());
          this.serviceData = (res.json());
          return this.serviceData || {};
        }
      
        loaddata(): Observable<any> {
          return this.http.get(this.server_url) // define a variable server_url to assign the requested url
            .map(this.extractData);
        }
      }
      

      现在在您的组件的ngOnInit 方法中通过调用此服务方法获取值。

      class MyComponent{
          constructor(public _myService: MyService)
          ngOnInit(){
            this._myService.loaddata().subscribe(data => {
            // do something with the data
          })
      
         }
      }
      

      【讨论】:

      • 在 .map() 之后使用 .subscribe 总是很重要吗?
      • @techiequestie,是的,这很重要。由于 API 例如loaddata 返回一个 Observable,我们需要订阅它才能真正执行 http 请求。
      猜你喜欢
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2019-05-02
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多