[英]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.