首页 > 解决方案 > 在 Angular 中使用 Observable 进行 http post 同步

问题描述

我正在尝试实现这一点,但需要一些帮助(我是新手)。

我目前有,

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 同步(在继续之前需要结果 [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 };
}));
}
}
}

但我认为这种语法是错误的。这会产生编译错误。有人可以在这里澄清使用地图功能的正确方法吗?

标签: angularhttppostobservablesynchronous

解决方案


从 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);

推荐阅读