Reputation: 7755
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());
}
);
}
}
Upvotes: 2
Views: 138
Reputation: 28259
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 Angular4.3+
so as you mentioned in comments you are already using one of these versions so I would recommend to switch toHttpClient
then.
Upvotes: 2