createAndStorePost(id: string, name: string, description: string,domain: string) {
const postData: Post = { id , domain , name, description };
this.http.post<{ id: number, name: string , description: string , domain: string }
(
'https://hamaaa-ff9ee.firebaseio.com/',
postData,
{
observe: 'response'
}
);
}}
此代码正确吗? 我想在邮递员api中发布数据
答案 0 :(得分:0)
我刚刚写了如何使用HttpClient将数据以角度发送到服务器。
//这是我要发布的模型
product: BrandSetupModel = {
id: 1,
brandName: 'Apple',
}
this.saveBrandSetup(product)
.subscribe((data: any) => {
console.log(data);
}, (error: any) => {
console.log(error);
}
)
saveBrandSetup(BrandSetup: BrandSetupModel) {
return this._http.post('http://localhost:9094/'+ 'api/CrmBrandSetup/Create', BrandSetup,
this.requestOptions)
.catch(this.errorHandler)
}
requestOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('userToken'),
})
};
errorHandler(error: Response) {
console.log(error);
return Observable.throw(error);
}
答案 1 :(得分:0)
让我们从post
的{{1}}定义开始吧!
HttpClient
它看起来像您自己的实现吗?不,让我们尝试对其进行一些更改
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
提到我如何删除那里的观察选项?如果您希望进行以下操作,请重新放回原位:
通过观察选项告诉HttpClient您想要完整的响应:
createAndStorePost(id: string,name: string,description: string, domain: string) {
// Create your Post Data (remember, second parameter)
const postData: any = { id: number, name: string , description: string , domain: string};
// No option, you just want to subscribe here
this.http.post('https://hamaaa-ff9ee.firebaseio.com/',postData).subscribe(
(result) => {
// do stuff with the result
}
);
}
现在HttpClient.get()返回HttpResponse类型的Observable,而不仅仅是JSON数据。
因此,使用此选项,您将不会获取JSON数据,而会获得包装函数。