2017-09-06 180 views
2

我需要幫助在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

回答

2

看起來你缺少.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