8

My $http call looks like this and I would like to know the most flexible way to handle all of the parameters that are returned in the .success and .error?

this.$http({ url: "/api/x, method: "GET" })
   .success((??) : void => {

   })
   .error((??) : void => {

   })

The Angular documentation tells me the following are returned:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

angular.d.ts shows me:

interface IHttpPromiseCallback<T> {
        (data: T, status: number, headers: (headerName: string) => string, config: IRequestConfig): void;
    }

    interface IHttpPromiseCallbackArg<T> {
        data?: T;
        status?: number;
        headers?: (headerName: string) => string;
        config?: IRequestConfig;
        statusText?: string;
    }

But I am still confused. Has anyone used the two interfaces above to define the callbacks and how did they do it?

Ideally I would like to have something like this:

 .success((data: any, status: number, headers: (headerName: string) => string, config: any) : void => {

But using the interfaces.

Can anyone tell me if I am on the right track and if I could use the interfaces rather than having to specify the :any :number etc after the parameters.

3 Answers 3

6

I realize this is a very old post, but I don't think the answers here are adequate (even for way-back-when, when this question was asked).

status is always going to be a number, so don't worry about that parameter.

You are likely seeking a way to handle the response in a strongly typed way.

The first property, data, is probably the main one you're concerned with. In your time, that .success/.error arg would be defined like:

this.$http({ url: "/api/x, method: "GET" })
   .success((response: IHttpPromiseCallbackArg<IMyInterface>) : void => {
        console.log("Hello "+ response.data.firstName);
   })
   .error((response: IHttpPromiseCallbackArg<IMyInterface>) : void => {

   })

Here in the future, .success and .error are deprecated and $http should be handled more like a standard promise:

this.$http({ url: "/api/x, method: "GET" })
    .then((response: IHttpPromiseCallbackArg<IMyInterface>) => {
        console.log("Hello "+ response.data.firstName);
    }, (response: IHttpPromiseCallbackArg<IMyInterface>) => {
        console.log("Boo, error code "+ response.status);
    });

And those are both assuming you have the data coming from your web service that fits the following:

export interface IMyInterface {
    firstName: string
}

UPDATE 12/4/2017

Whoa, it's me again from even further in the future! Now IHttpPromiseCallbackArg is deprecated. Things here in the future sure are complicated. How I long for simpler times.

(J/K it's actually easier now.)

Instead of IHttpPromiseCallbackArg<>, use: IHttpResponse<>. It appears the interface signature is mostly (completely?) the same and is a drop-in replacement.

this.$http({ url: "/api/x, method: "GET" })
    .then((response: IHttpResponse<IMyInterface>) => {
        console.log("Hello "+ response.data.firstName);
    }, (response: IHttpResponse<IMyInterface>) => {
        console.log("Boo, error code "+ response.status);
    });
Sign up to request clarification or add additional context in comments.

Comments

3

Here's and example for the GET:

  private getInternal<T>(url) {
        var deferred = this.$q.defer();

        this.$http({ url: url, method: "GET" })
            .success((data: T, status: number, headers: (headerName: string) => string, config: ng.IRequestConfig): void => {
                if (status == 200 && headers('location') == null && config.timeout > 200) {
                    //do something with data
                }

                return deferred.resolve(data);
            })
            .error((data: T, status: number, headers: (headerName: string) => string, config: ng.IRequestConfig): void => {
                if (status == 500 && headers('myAuth') != null && config.method == 'GET') {
                    // write to log
                }

                return deferred.reject(data);
            });
    }

Now let's say you have a service and you know your getting a specific object:

this.getInternal<mySpecObject>('service/abc').then(res => doSomethingWithData(res));

3 Comments

Where does 'req' in 'var deferred in req.deferred' come from?
@TorbenRahbekKoch, it has to be $q:ng.IQService (docs.angularjs.org/api/ng/service/$q)
I suppose getInternal should also return an object. angular.IDeffered<T> or angular.IPromise ? then you call the .then
3

here is what i did

module portal.services {


export class apiService {


    public getData<T>(url?:string): ng.IPromise<T> {

        var def = this.$q.defer();
        this.$http.get(this.config.apiBaseUrl + url).then((successResponse) => {

            if(successResponse)
                def.resolve(successResponse.data);
            else
                def.reject('server error');

        }, (errorRes) => {

            def.reject(errorRes.statusText);
        });

        return def.promise;
    }

    public postData<T>(formData: any, url?:string,contentType?:string): ng.IPromise<T>{

        var def = this.$q.defer();

        this.$http({
            url: this.config.apiBaseUrl + url,
            method: 'POST',
            data:formData,
            withCredentials: true,
            headers: {
                'Content-Type':contentType || 'application/json'
            }
        }).then((successResponse)=>{
            def.resolve(successResponse.data);
        },(errorRes)=>{
            def.reject(errorRes);
        });

        return def.promise;

    }

    static $inject = ['$q','$http', 'config'];

    constructor(public $q:ng.IQService,public $http:ng.IHttpService, public config:interfaces.IPortalConfig) {


    }

}

}

1 Comment

Can you give me an example of how to use getData in a controller?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.