无法从Angular中获取Http的响应

时间:2017-09-06 03:16:57

标签: javascript angular angular-services angular-http

我需要帮助在ngOnInit()期间从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());
        }
      );
  }

}

1 个答案:

答案 0 :(得分:2)

您似乎缺少.subscribe()

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

这就是观察者的工作方式。如果你没有订阅它就不会被执行

<强>更新 以下"how to http"取自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);
    });
  }
}
  

上面的示例使用了新的'@angular/common/http'   Angular 4.3+正如您在评论中提到的那样,您已经在使用   其中一个版本所以我建议切换到HttpClient   然后