在角度1x中,我能够在服务中分离我的Web服务调用,如下所示.
angular.module('app.APIServices', []) .factory('API', ['serviceBase', 'clientConfig', '$http', 'cacheService', function(serviceBase, clientConfig, $http, cacheService) { return { getSystemStats: function(params) { var params = _.merge(params, serviceBase.baseParams); return $http({ url: serviceBase.serviceBaseUri + '/GetSystemStats', method: 'POST', data: params, cache: false }).then(function(response) { return response.data; }) } // more methods in a similar way can be added. } } );
然后在控制器中使用上述服务:
API.getSystemStats(paramsObject).then(function(result){ // run success logic here },function(reason){ // run failure });
我想在Angular2中实现相同的分离.我想避免在所有组件中定义webservice URL.
实现这一目标的最佳方法是什么?
您也可以在Angular 2.0中将http服务包装在您自己的服务中.
这是一个例子:
import {Http, Response} from '@angular/http' import {Injectable} from '@angular/core' @Injectable() export class AddressBookService { http:Http; constructor(http:Http){ this.http = http; } getEntries(){ return this.http.get('./people.json').map((res: Response) => res.json()); } }
然后可以将上面定义的服务导入到组件中,如下所示:
@Component({ selector: 'address-book', templateUrl: './components/dependency-injection/address-book.html', providers:[AddressBookService] }) export class AddressBook { result:Object; constructor(addressBookService:AddressBookService){ this.result = {people:[]}; addressBookService.getEntries().subscribe(res => this.result = res); } }
服务需要@injectable以解决组件和服务的完整DI依赖关系链.
在这种情况下,服务在组件级别注册为提供者.您还可以在应用程序级别通过在应用程序引导方法中指定它来注册它.
这里有更多信息:http://www.syntaxsuccess.com/viewarticle/dependency-injection-in-angular-2.0
以下是该示例的完整来源:https://github.com/thelgevold/angular-2-samples/tree/master/components/dependency-injection