2017-09-06 7 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。コンソールには何もありません – 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 http"How to make post request from angular to node serverから取っている:上記の例はそう 角度4.3+に出荷された新しい'@angular/common/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); 
    }); 
    } 
} 

コメントで言及したように、既に のいずれかを使用していますので、HttpClient に切り替えることをお勧めします。

+0

どこに追加しますか?どのように私はそれを書くのですか? – Joseph

+0

ありがとうございます。トークンは提供されていません。私のletヘッダー=新しいヘッダー(); 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インターセプタを使用してそれを行うこともできます。 – Kuncevic

関連する問題