2016-07-28 57 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 
    });