0

For a test I have the following code added to my test.ts, which I included in the main.ts.

var http:Http;
let headers = new Headers();
headers.set('Accept', 'text/json');
let url = 'http://localhost:8080/usersdto';

http.get(url, { headers})
  .subscribe(resp => showResponse(resp), err => showResponse(err));

So this is no Class, just typescript. I get the error pointing to line 'http.get' (showResponse exists as function):

Uncaught TypeError: Cannot read property 'get' of undefined

Why do I get this Error and how do I define the http object correctly ?

1 Answer 1

1

First you need to import HttpClient from @angular/common/http. Then you define the http object by injecting it into the constructor of the class you want to use it in.

All of what you need and best practices are explained in this example.

Hope that helps.

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

2 Comments

So I can't do it like I did for testing only ?
HttpClient is available as an injectable class, so there's no way to use it without injecting it.

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.