2016-07-28 36 views
1

我試圖做一個http.get請求從本地目錄中獲取文件,此刻我只想要console.log api得到的響應正在請求。 getFile()顯示console.log但調用http,不確定在angular2中如何使用http;我知道在angular1中使用.then作爲迴應。angular2調用http.get請求打開文件

import { Http, HTTP_PROVIDERS } from '@angular/http'; 

getFile() { 
    this.http.get('//localhost:1337/getFile'); 
    console.log('get me the file'); 
} 

阿比端點:

app.get('/getFile', function(req, res) { 
    var contents = fs.readFileSync('journey.xml'); 
    console.log('Reading File....' + contents); 
    res.send(contents); 
}); 

回答

0

您需要申請可觀察到的由HTTP服務返回:

import { Http, HTTP_PROVIDERS } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

getFile() { 
    this.http.get('//localhost:1337/getFile') 
    .map(response => response.text()) 
    .subscribe(data => console.log('get me the file', data)) 
} 
+0

我得到「與狀態未捕獲的響應:0網址:空」錯誤和GET http:// url/getFile空回覆 – nCore

+0

如果您在新標籤中打開// localhost:1337/getFile,它會向您展示什麼? – dfsq

+0

對不起,我的api服務器沒有運行。我在console.log中獲取數據,但是當我調用getFile()時,我怎麼才能打開/下載文件?如果我打開/ getFile在另一個選項卡下載文件。 – nCore

0

嘗試使用訂閱

.subscribe(
    res => this.somename= res.json(), 
    error => console.log(error)); 

OR

.subscribe(
    function(response) { console.log("Success Response" + response)}, 
    function(error) { console.log("Error happened" + error)}, 
    function() { console.log("the subscription is completed")} 
); 
+0

你能解釋你的答案嗎? this._OBJ_從哪裏來的? – nCore

+0

this._OBJ_僅僅是一個例子,你只需定義一些名字並賦值給res.json(); – Sridhar

0

http.get方法返回一個可觀察HTTP響應的 你可能會想嘗試這樣的事:

this.http.get('//localhost:1337/getFile').subscribe(f => { 
     console.log(f) 
    }, (error) => { 
     //handle error 
    },() => { 
     //complete 
    });