如何从服务

时间:2017-12-10 08:32:19

标签: angular2-services angular2-http angular4-httpclient

我如何从邮寄服务中获取数据,因为我总是订阅。即使我尝试在我的应用程序组件中转换,我也无法做到。

facility_sevice.ts

saveFacility(facility) { 
    const headers = new Headers({'Content-Type': 'application/json'});
    return this.http.post('http://localhost:8000/saveFacility', 
facility, headers)
    .subscribe(
    (response: Response) => {
    return response.json();
},
(error) => {
return error.json();
}
);
}

facility_component.ts

savePatient() {
const response = 
this.facilityService.saveFacility(this.facilityForm.value)
console.log(response);
}

我正在获取sbscription对象,但我想以json的身份返回。

1 个答案:

答案 0 :(得分:3)

RxJS库提供了Observable操作符,您可以使用它来操作像map,filter这样的数据。

尝试使用地图运算符:

    saveFacility(facility) { 
        const headers = new Headers({'Content-Type': 'application/json'});
        return this.http.post('http://localhost:8000/saveFacility', facility, headers)
            .map(response => response.json())
            .subscribe((response: Response) => {
                    return response.json();
                },
                (error) => {
                    return error.json();
                }
            );
    }