如何在component.ts中获取可见数据来自Service(Observable pattern)

时间:2018-04-06 06:20:41

标签: angular angular2-forms angular2-services angular2-directives

service .ts

 get_update(id:any): Observable<any[]>{
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://localhost:8000/vendor/'+id,options)
                        .map(response => response.json())
                        .catch(error => Observable.throw(error.statusText));       
}
component.ts

ngOnInit()

{    this.service.get_update(this.user).subscribe(data =&gt; console.log(data));

}

我想将数据存储到另一个变量中,我想转换为全局变量

3 个答案:

答案 0 :(得分:1)

我想你想记录回复? 你只需要

this.service.get_update(this.user).subscribe(update => console.log(update),
                                                      error => console.log(error));

答案 1 :(得分:0)

您可以记录响应,也可以在模板中插入更新变量的值。

this.service.get_update(this.user).subscribe((response) => {
    this.varibleName = response;
    console.log(this.varibleName);
}, (error) => {
    console.log(error);
});

或在模板中

{{variableName | json}}

答案 2 :(得分:0)

此外,还可以选择使用异步管道

&#13;
&#13;
import json
from pprint import pprint
data = json.load(open('File Path'))
pprint(data['fullTextAnnotation']['text'])
&#13;
&#13;
&#13;

并在您的模板中

&#13;
&#13;
   this.serviceData = this.service.get_update(this.user).map(res => res.json())
&#13;
&#13;
&#13;