Reputation: 17825
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
formData = {
first_name:"",
last_name:"",
middle_name:"",
mobile_number:"",
email_address:"",
password:"",
confirm_password:""
};
constructor(private httpClient:HttpClient) {
}
ngOnInit() {
console.log(this.httpClient.get("http://localhost:8000"));
// how to use this returned Observable to get the actual response.
}
submittedDetails(){
console.log('FirstName: ' + this.formData.first_name);
console.log('LastName: ' + this.formData.last_name);
console.log('MiddleName: ' + this.formData.middle_name);
console.log('Email Address: ' + this.formData.email_address);
console.log('MobileNumber: ' + this.formData.mobile_number);
console.log('Password: ' + this.formData.password);
console.log('Confirm Password: ' + this.formData.confirm_password);
}
}
I am playing around with the above code to get the HTTP response. Right now, I am learning Angular. The reason to make a HTTP call on ngInit()
is purely for learning purpose.
I am using Angular 6.
Difficulty/Issue:
I able to make a request to my back end code and code inside ngInit()
returns me an Observable
. Now, how to use this to see the actual response received?
Let's assume Content-type of response could be anything for now. I apologize if I have understood anything wrong(in Angular context) here.
Upvotes: 0
Views: 13852
Reputation: 148
If you want to trigger the request in your component/service you have to subscribe to it.
this.httpClient.get("http://localhost:8000").subscribe(response => {
// do some action
});
Upvotes: 1
Reputation: 4039
You must subscribe to observable:
this.httpClient.get("http://localhost:8000").subscribe(data => {
console.log(data);
});
Note that by default httpClient
expects to receive JSON and parses that for you. If your reply returns something else, you should modify the request.
Upvotes: 3