2

i need help in getting a response from http during ngOnInit(). I put an alert("hello") and it's not alerting anything. Is there something wrong in my code?

import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/Rx';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})

@Injectable()
export class DashboardComponent implements OnInit {

  constructor(private http: Http) { }

  ngOnInit() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let authToken = localStorage.getItem('auth_token');
    headers.append('Authorization', `Bearer ${authToken}`);

    return this.http
      .get('http://sampeleposts', { headers })
      .map(
        response => {
          console.log(response);
          alert("hello");
        },
        error => {
          alert(error.text());
          console.log(error.text());
        }
      );
  }

}
2
  • Did you look for errors in the Console? Commented Sep 6, 2017 at 3:32
  • @nitind. Theres nothing in the console Commented Sep 6, 2017 at 3:33

1 Answer 1

2

Looks like you are missing .subscribe()

return this.http
      .get('http://sampeleposts', { headers })
      .subscribe(
        response => {
          console.log(response);
          alert("hello");
        },
        error => {
          alert(error.text());
          console.log(error.text());
        }
      );

That is how observables works. If you won't subscribe it won't executed

UPDATE: Here is "how to http" taking from How to make post request from angular to node server:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user = { id : 1, name : 'Hello'};

  constructor(private http: HttpClient) { }

  callServer() {
    const headers = new HttpHeaders()
          .set('Authorization', 'my-auth-token')
          .set('Content-Type', 'application/json');

    this.http.post('http://127.0.0.1:3000/ping', JSON.stringify(this.user), {
      headers: headers
    })
    .subscribe(data => {
      console.log(data);
    });
  }
}

The example above is using the new '@angular/common/http' shipped in Angular 4.3+ so as you mentioned in comments you are already using one of these versions so I would recommend to switch to HttpClient then.

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

11 Comments

Where do i add it? How do i write it?
Thank you. it now says token not provided. Is there wrong in my let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token'); headers.append('Authorization', Bearer ${authToken});
@Joseph I just updated the answer with some details using new @angular/common/http It is showing how to pass HttpHeaders() right. Also you might use http interceptors to do that, if you want angular.io/guide/http#advanced-usage.
@Joseph are you using angular 4.3+ btw?
Yes. But i'm still using the http only. But I heard HttpClient is the new one.
|

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.