angular - 在 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 };
}));
}
}
}
但我认为这种语法是错误的。这会产生编译错误。有人可以在这里澄清使用地图功能的正确方法吗?
解决方案
从 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);
推荐阅读
- android - 带有进度乘数的搜索栏
- python - 为什么 np.empty() 和 np.zeros() 返回不同的值?
- sql-server - SSIS-SQL 部署
- javascript - 每个 Cypress.io cy.route() 调用的随机响应
- intellij-idea - 如何在 Mac 上的 Intellij/Pycharm 运行/调试配置中配置 Azure 函数项目
- c# - 向数据库添加条目后 Blazor 组件不刷新
- linux - 虚拟地址空间
- git - Gitlab 存储库大小太大
- python - Django-mptt 未在模板中列出名称
- python - SpyderKernelAppn警告 | 没有这样的通讯:2ed06aee37e411eb867974e5f9ff3c18 (OPENCV)