无法从角度获得Http响应

问题描述:

我需要帮助在ngOnInit()期间从http获取响应。我发出警报(“你好”),它没有提醒任何事情。我的代码有问题吗?无法从角度获得Http响应

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

} 
+0

您是否在控制台中查找错误? – nitind

+0

@nitind。 Theres没有在控制台 – Joseph

看起来你缺少.subscribe()

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

那是怎样可观测量工作。如果你不认购就不会执行

UPDATE: 这里是How to make post request from angular to node server采取"how to http"

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

上面的例子是使用运 角4.3+所以新'@angular/common/http'正如你在评论中提到的,你已经在使用 其中一个版本,所以我建议你切换到HttpClient

+0

我在哪里添加它?我如何写它? – Joseph

+0

谢谢。它现在说令牌不提供。有没有错我的头文件=新的头(); headers.append('Content-Type','application/json'); let authToken = localStorage.getItem('auth_token'); headers.append('Authorization','Bearer $ {authToken}'); – Joseph

+0

@Joseph我刚刚使用新的'@ angular/common/http'更新了一些细节的答案,它展示了如何传递'HttpHeaders()'的权利。如果你想要https://angular.io/guide/http#advanced-usage,你也可以使用'http interceptors'来做到这一点。 – Kuncevic