[英]make http post synch using Observable in Angular
我正在尝试实现此功能,但需要一些帮助(我是新手)。
我目前有
constructor(http: HttpClient, private cvservice: CvService) {
const req = http.post<any>('url', [{
"name": "ids",
"license": "GPL version 2"
}])
.subscribe(
res => {
console.log(res);
var resp = res.Results[0].results.map(x => {
return {cvid: x.ID, severity: x.CVSS };
} );
this.data = [...resp];
},
err => {
console.log("Error occured");
}
);
}
除我需要使http.post同步(继续之前需要Results [0])并且我正在使用来自如何同步Angular2 http get的建议外,此方法工作正常。 。
我已将服务修改为
export class CvService {
constructor(private http: HttpClient) {
}
url = 'foo';
getIds():Observable<any[]> {
const url='xxx';
return this.http.post(url, [{
"name": "ids",
"license": "GNU General Public License GPL version 2"
}])
.map(
res => {
res.Results[0].results.map( x => {
return {cvd: x.ID, severity: x.CVSS };
}));
}
}
}
但是我认为这种语法是错误的。 这会产生编译错误。 有人可以在这里说明使用地图功能的正确方法吗?
从rxjs导入地图,并像这样在管道内使用它
return this.http.post(URL, Object)
.pipe(map(data) => {
return data['result'].map(res => {
// Here You can return the entire res, or just the properties you want
// EX: --> return res OR --> return res.cvd
});
});
另外,把物体放在外面
let cv = [{
name: "ids",
license: "GNU General Public License GPL version 2"
}];
你可以这样使用它
return this.http.post(URL, cv);
您可以通过以下方式实现:
服务
saveUser(): Observable<any> {
const data = [{"name": "ids", "license": "GNU General Public License GPL version 2"}];
// For Angular v5 below
this.http
.post(url, data)
.map(res => res.json()); // or .map(res => res), depends what your fetching with
OR you can pipe it out (Angular 6+)
this.http
.post(url, data)
.pipe(map(({ Results }: any) => Results[0].results.map(item => ({cvid: item.ID, severity: item.CVSS }))));
// Based from you code when you accessed it this way: res.Results[0].results.map( x => {return {cvd: x.ID, severity: x.CVSS };
}
零件
this.userService
.saveUser()
.subscribe(data => console.log(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.