简体   繁体   English

Angular 2 HTTP GET等效于Angular HTTP GET

[英]Angular 2 HTTP GET Equivalent to Angular HTTP GET

Hope someone can clarify something for me. 希望有人可以为我澄清一些事情。 What I am doing right now, working with Angular 1.4.6: 我正在做什么,使用Angular 1.4.6:

I create a service 我创建了一个服务

'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           
        };
    }
]);

And use/inject that in my controller. 并在我的控制器中使用/注入。

'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);
}]);

I started a little bit playing around with angular2 beta and found the following example on http.get 我开始尝试使用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);
}

I build some other methods and tested a bit around and googled a lot, but could not find anything similar in creating a service with angular2 beta and typescript the way I was doing till now. 我构建了一些其他方法并进行了一些测试并搜索了很多东西,但在创建一个与angular2 beta和typescript一样的服务方面却找不到类似的东西。 Is it even necessary to do it that way. 甚至有必要这样做。 Or is this not the way it is done now with Angular2 beta? 或者这不是现在使用Angular2 beta的方式吗?

Thank you in advance. 先感谢您。

You can simply return an observable object (what the http.get method returns) from your your service, ie a class with the Injectable annotation: 您可以从服务中返回一个可观察对象( 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());
  }
}

Within your component, you can then inject this service and call the method that actually executes the HTTP request. 在组件中,您可以注入此服务并调用实际执行HTTP请求的方法。 To get the result, just use the subscribe method: 要获得结果,只需使用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')
    );
  }
}

You could have more details at this address: How to Consume Http Component efficiently in a service in angular 2 beta? 您可以在此地址获得更多详细信息: 如何在角度2 beta的服务中有效地使用Http组件? .

Hope it will help you, Thierry 希望它会帮助你,蒂埃里

Services in angular 2 are just TypeScript classes decorated with the @Injectable() . 角度2中的服务只是使用@Injectable()修饰的TypeScript类。

The service could look like this: 该服务可能如下所示:

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;
  }
}

Then you can use dependency injection to insert the service in a component, like this: 然后,您可以使用依赖注入将服务插入组件中,如下所示:

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);
      });
  }
}

The template for that component: 该组件的模板:

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

You also need to configure the global inject to allow for the injection of the Http service. 您还需要配置全局注入以允许注入Http服务。

import {bootstrap} from 'angular2/platform/browser';
import {HttpWorkApp} from './app/http-search-params';
import {HTTP_PROVIDERS} from 'angular2/http';

bootstrap(HttpWorkApp, [HTTP_PROVIDERS]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM