简体   繁体   中英

Angular2: Code organisation of web service/http requests

In angular 1x, I was able to separate my web service calls in a service as shown below.

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

and then use the above service in the controller:

API.getSystemStats(paramsObject).then(function(result){
    // run success logic here
},function(reason){
    // run failure
});

I would like to implement the same separation in Angular2 . I would like to avoid defining the webservice urls in all the components.

What would be the best way to achieve this?

You can wrap the http service in your own service in Angular 2.0 as well.

Here is an example:

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

}

The service defined above can then be imported into a component like so:

@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 is needed on the service in order to resolve the full DI dependency chain for both the component and the service.

In this case the service is registered as a provider at the component level. You can also register it at the application level by specifying it in the application bootstrap method.

Some more info here: http://www.syntaxsuccess.com/viewarticle/dependency-injection-in-angular-2.0

Here is the full source for the example: https://github.com/thelgevold/angular-2-samples/tree/master/components/dependency-injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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