我正在向服务器发送发帖请求,而从服务器端,我只会得到一个空的正文。
我的客户很棱角。
这是发送请求的服务的代码:
public constructor(private http: HttpClient) { }
public addImagePair(gameName: string, originalImage: File, modifiedImage: File): Observable<ICommonImagePair> {
const formData: FormData = new FormData();
formData.append("name", gameName);
formData.append("originalImage", originalImage);
formData.append("modifiedImage", modifiedImage);
new Response(formData).text().then(console.log);
return this.http.post<ICommonImagePair>(this.BASE_URL + "image-pair", formData);
}
public addGameCard(gameName: string, imagePairId: string, pov: POVType): Observable<ICommonGameCard> {
const formData: FormData = new FormData();
formData.append("name", gameName);
formData.append("image-pair-id", imagePairId);
formData.append("pov", "Simple");
new Response(formData).text().then(console.log);
return this.http.post<ICommonGameCard>(this.BASE_URL + "gamecard", formData);
}
这是调用服务的组件的代码:
public addImagePair(): void {
this.simplePOVGameGeneratorService.addImagePair(this.gameName, this.originalImageFile, this.modifiedImageFile)
.subscribe((imagePair: ICommonImagePair) => {
this.simplePOVGameGeneratorService.addGameCard(imagePair.name, imagePair.id, POVType.Simple)
.subscribe((gameCard: ICommonGameCard) => {
console.log(gameCard);
});
});
}
在组件中,我首先请求addImagePair()
,该请求确实发送了请求,没有任何问题。然后,我用几乎相同的代码调用addGameCard()
,但主体却是空的。我在提出请求之前先控制台日志,以确保确实有数据。我还在服务器上控制台登录,主体为空。到底是什么原因造成的?
答案 0 :(得分:1)
您可以使用flatMap
运算符,而不是手动订阅如下所示的嵌套可观察对象-
public addImagePair(): void {
this.simplePOVGameGeneratorService.addImagePair(this.gameName, this.originalImageFile, this.modifiedImageFile)
.flatMap((imagePair: ICommonImagePair) => this.simplePOVGameGeneratorService.addGameCard(imagePair.name, imagePair.id, POVType.Simple))
.subscribe((gameCard: ICommonGameCard) => {
console.log(gameCard);
});
});
}
您还可以在post方法中将数据作为字符串文字而不是FormData
传递,例如formdata = { "name":gameName,"image-pair-id":imagePairId,"pov": "Simple"}
,然后在return this.http.post<ICommonImagePair>(this.BASE_URL + "image-pair", JSON.stringify(formData));
方法中使用addGameCard
。