1

How to use the HTTP service provided by Angular2 in ES5 code? Here is the TypeScript example.

I basically need examples of GET and POST requests.

The example shown here is not working. get seems to be undefined.

Here is an example that doesn't work:

    var SearchResultComponent = ng.core.Component({
        selector: "search-result",
        viewProviders: [ng.http.HTTP_PROVIDERS],
        templateUrl: "componentTemplates/SearchResult.html"
    }).Class({
        constructor: [ng.http.HTTP_PROVIDERS, function(http) {
            this.params = params;
            this.http = http;
        }],
        ngOnInit: function(){

            console.log(this.http.get); //undefined
        }
    })
2
  • You could make it a valid question by adding the code that demonstrates what you tried and the exact error message you got. A Plunker that demonstrates the issue wouldn't hurt either. Commented May 9, 2016 at 7:18
  • done. edited post and added an example. Commented May 9, 2016 at 7:42

1 Answer 1

0

In the constructor of your SearchResultComponent component, you need use ng.http.Http and not HTTP providers:

var SearchResultComponent = ng.core.Component({
    selector: "search-result",
    viewProviders: [ng.http.HTTP_PROVIDERS],
    templateUrl: "componentTemplates/SearchResult.html"
}).Class({
    constructor: [ng.http.Http, function(http) { // <-----
        this.params = params;
        this.http = http;
    }],
    ngOnInit: function(){

        console.log(this.http.get); //undefined
    }
});

In your case, it wasn't the Http object that was injected...

Providers can be specified when boostrapping your application, in the providers attribute or the viewProviders attribute (like you did).

See this plunkr for a use of HTTP with Angular2 and ES5: https://plnkr.co/edit/oM4gTgW5Q7gpR8Qderjj.

Sign up to request clarification or add additional context in comments.

3 Comments

what is the difference between viewProviders and the array values assigned to the constructor. I mean difference between HTTP_PROVIDERS and ng.http.Http?
viewProviders / providers allow you to define providers (entities responsible of creating instances of something) and constuctor parameters to what you want to inject (i.e. objects created by providers)
HTTP_PROVIDERS are the providers for HTTP and ng.http.Http the type of the object you want to inject. One of providers knows how to create an instance of this type...

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.