【问题标题】:Angular2: Code organisation of web service/http requestsAngular2:Web服务/http请求的代码组织
【发布时间】:2016-03-27 03:40:42
【问题描述】:

在 Angular 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 中实现相同的分离。我想避免在所有组件中定义 web 服务 url。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您也可以在 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

    【讨论】:

    • 谢谢你,它工作得很好,谢谢你在 www.syntaxsuccess.com 上的文章,它们确实很有帮助。
    • 如何将参数传递给 getEntries() ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2016-06-10
    • 2015-11-12
    • 2011-11-19
    相关资源
    最近更新 更多