nice_dev
nice_dev

Reputation: 17825

Use observable to get the HTTP response

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

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

Answers (2)

Saso
Saso

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

PeS
PeS

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

Related Questions