在 Angular 中无法从 Http 获得响应

Can't Get Response From Http in Angular

我需要帮助才能在 ngOnInit() 期间从 http 获取响应。我发出警报 ("hello") 但它没有发出任何警报。我的代码有问题吗?

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

}

看来你不见了.subscribe()

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

Observables 就是这样工作的。如果你不订阅它就不会执行

更新: 这是 "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);
    });
  }
}

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.