【问题标题】:Angular 2 HTTP GET Equivalent to Angular HTTP GETAngular 2 HTTP GET 等效于 Angular HTTP GET
【发布时间】:2016-04-03 05:39:00
【问题描述】:

希望有人可以为我澄清一些事情。 我现在正在做什么,使用 Angular 1.4.6:

我创建一个服务

'use strict';
angular.module('App')
.factory('processingService', ['$http',
    function ($http) {
        var settings = 'Settings/GetSettings';    
        var getSettings = function()
        {
            return $http.get(settings)
                .then(function(response)
                {
                    return response.data;
                });
        };
        return {
            getSettings: getSettings           
        };
    }
]);

并在我的控制器中使用/注入它。

'use strict';
angular.module('App')
.controller('appController', [
    '$scope','appService',
    function ($scope, appService) {     
        var onSettings = function (data) {
            if (data.hasOwnProperty('Settings')) {    
                //Code handling Settings          
            }
        };
        var onSettingsError = function()
        {
           //Handle Errors
           $scope.showLoader = false;
        };      
        appService.getSettings()
            .then(onSettings, onSettingsError);
}]);

我开始使用 angular2 beta 并在 http.get 上找到了以下示例

getRandomQuote() {
  this.http.get('http://localhost:3001/api/random-quote')
    .map(res => res.text())
    .subscribe(
      data => this.randomQuote = data,
      err => this.logError(err),
      () => console.log('Random Quote Complete')
    );
}

logError(err) {
  console.error('There was an error: ' + err);
}

我构建了一些其他方法并进行了一些测试并搜索了很多,但在使用 angular2 beta 和 typescript 创建服务时找不到任何类似的东西,就像我到目前为止所做的那样。 是否有必要这样做。 或者这不是现在使用 Angular2 beta 的方式吗?

提前谢谢你。

【问题讨论】:

    标签: typescript angular angular2-services


    【解决方案1】:

    Angular 2 中的服务只是用 @Injectable() 修饰的 TypeScript 类。

    服务可能如下所示:

    import {Injectable, Inject, EventEmitter} from 'angular2/core';
    import {Http, Response} from 'angular2/http';
    
    @Injectable() // annotated class that can be injected in other components
    export class ProcessingService {
      // inject the http service (configured in the global injector)
      constructor(@Inject(Http) private http :Http) {
    
      }
      // the service method returning an event emmiter (instead of promises)
      public getSettings():EventEmitter<string> {
    
          let emmiter = new EventEmitter<string>(true);
    
          // call the method and subscribe to the event emmiter
          this.http.get('Settings/GetSettings').subscribe((value: Response) => {
            emmiter.emit('called');    
          });
          return emmiter;
      }
    }
    

    然后你可以使用依赖注入将服务插入到组件中,如下所示:

    import {Component, Inject } from 'angular2/core';
    // import our service
    import {ProcessingService} from './services/processing-service/processing-service';
    
    @Component({
      selector: 'http-search-params-app',
      providers: [],
      templateUrl: 'app/http-search-params.html',
      pipes: [],
      bindings:[ProcessingService] // tell the component injector to inject our service
    })
    export class HttpWorkApp {
      workDone = [];
    
      constructor(private processingService: ProcessingService) {}
    
      // call the sevice 
      public doWork() {
          this.processingService.getSettings().subscribe((value :string) =>{
              this.workDone.push(value);
          });
      }
    }
    

    该组件的模板:

    <div>
        <button (click)="doWork()">Call HTTP Service</button>
        <div *ngFor="#workItem of workDone">{{workItem}}</div>    
    </div>
    

    您还需要配置全局注入以允许注入 Http 服务。

    import {bootstrap} from 'angular2/platform/browser';
    import {HttpWorkApp} from './app/http-search-params';
    import {HTTP_PROVIDERS} from 'angular2/http';
    
    bootstrap(HttpWorkApp, [HTTP_PROVIDERS]);
    

    【讨论】:

      【解决方案2】:

      您可以从您的服务中简单地返回一个可观察对象(http.get 方法返回的内容),即带有 Injectable 注释的类:

      @Injectable()
      export class CompanyService {
        constructor(http:Http) {
          this.http = http;
        }
      
        getRandomQuote() {
          return this.http.get('http://localhost:3001/api/random-quote')
                        .map(res => res.json());
        }
      }
      

      然后,您可以在您的组件中注入此服务并调用实际执行 HTTP 请求的方法。要得到结果,只需使用subscribe 方法:

      export class CompanyList implements OnInit {
        public companies: Company[];
      
        constructor(private service: CompanyService) {
          this.service = service;
        }
      
        logError(err) {
        }
      
        ngOnInit() {
          this.service.getRandomQuote().subscribe(
            data => this.randomQuote = data,
            err => this.logError(err),
            () => console.log('Random Quote Complete')
          );
        }
      }
      

      您可以在此地址获得更多详细信息:How to Consume Http Component efficiently in a service in angular 2 beta?

      希望对你有帮助 蒂埃里

      【讨论】:

      • 我必须为此导入 Http 类型吗?如果有,来自哪里?
      • 是的,你必须这样做。来自@angular/http。请注意,Angular 现在为 http 提供了另一个模块:http 客户端。
      猜你喜欢
      • 2016-10-07
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2018-01-07
      • 2017-06-14
      • 2017-06-23
      相关资源
      最近更新 更多