Angular 2中的Api-Service和HTTP服务

时间:2016-10-24 11:37:01

标签: http angular typescript

我是Angular 2的新手,我有一个问题。 在我的“老”Angular 1 Webapps中,我每次都有“Api-Service”和“Http-Service”。 它们看起来像这样: “ApiService”:

    angular.module('ionicApp.apiServices', [])

    .service('apiService', function(httpService) {
        return {
            getProfile: function(){
                return httpService.async('get', 'profile', {}, {}, {});
            },
            addSkills: function(skillList) {
                var url = 'profile/skills';
                return httpService.async('post', url, {}, {}, skillList);
            }
}

HTTP-服务:

angular.module('ionicApp.httpService', [])

.service('httpService', function ($http, $rootScope, $state, $ionicLoading, $ionicHistory) {
var httpCall = {
        async : function (method, url, header, params, data) {
            // Setze den X-AUTH-TOKEN in den Header, welcher für die Authentifizierung des Users verantwortlich ist
            if (url != 'login' || url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
                header['X-AUTH-TOKEN'] = $rootScope.userToken;
            }
            header['Access-Control-Allow-Origin'] = '*';
            // $http returns a promise, which has a then function, which also returns a promise
            var promise = $http({
                    method : method,
                    url : ipurl + url,
                    headers : header,
                    params : params,
                    data : data,
                    timeout: 10000,
                    withCredentials : true
                }).then(function successCallback(response) {
                    if (url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
                        $rootScope.userToken = response.headers('X-AUTH-TOKEN');
                    }
                    return response;
                }, function errorCallback(response) {
                    if (response.status === 401) {
                        $rootScope.isFailure = true;
                        $rootScope.failure = "Sie haben keine gültige Session mehr. Bitte loggen Sie sich erneut ein.";
                        doLogout();
                    } else {
                        return response;
                    }
                });
            // Return the promise to the controller
            return promise;
        },
        doLogout : doLogout

    };
    return httpCall;
});

好的,现在我的问题是,我怎么能用角度2做到这一点? 我已经完成了Api-Service和HTTP-Service(两者都是Injectables),并在每个组件中注入它们。 但是让它们发挥作用的诀窍呢?

非常感谢!

0 个答案:

没有答案