如何将 json obj 值传递给 angular 中的 API(用于 post 方法)



在这里,我正在尝试将一些数据发布到 API。但它不起作用。因为我收到了 400 个错误请求。我认为我的服务或打字稿不好。当尝试邮递员时,我得到了 output.so 我确认我的 Web APi 工作正常。 其实我是新手 angular.so 请帮帮我,我是初学者。我在这里搜索了很多次,但没有得到答案。 在这里,我的 API 接受 JSON 的值目录 喜欢(注意我正在使用 angular4 web API(

{ 
"Header": {
"UserID": 6,
"created": "February 4, 2016 10:13:00",
....etc........
},
"detail": [
{
"ShopID": 1,
"ItemID": 126,
.....etc.........
},
{     
"ShopID": 1,
"ItemID": 127,
.....etc.........
}
]
}

但是我的数据传递给API就像(所以我认为这是问题所在(

[{
"userid": "64",
"created": "February 4, 2016 10:13:00",
"CompanyID": "1",
"modified": "February 4, 2016 10:13:00",
"modifieduserid": "65",
"confirm": "true",
"ShopId": 1,
"TransactionId": 1,
"shopid": 12,
"Itemid": 12928,
"PackingTypeID": 3,
"Itemcode": "124018",
"Itemdescription": "COTTON GLOVES 350G",
"PackingtypeName": "12 PCS",
"Stockcount": 12

} ]

这是我的ts文件

stockitems: IStockCountHeaders[] = [];   
items: IStockCountHeaders;
stockdetail: IStockdetails[] = [];
addItems(value: any) {
this.items = new IStockCountHeaders(this.userid, this.created, t this.confirm,this.shopid, 
value.ItemID, value.PackingTypeID, value.ItemCode, value.ItemDescription, 
value.PackingtypeName, 
value.Stock,
);
this.stockitems.push(this.items);
}
onclick(){
this._enqService.CatchStockDetailHeader(this.stockitems)
.subscribe(value => {
if (typeof value !== 'undefined' && value != null) {
value.forEach(items => {
this.stockitems.push(this.items)
});
}
},
error => {
console.error(error);
this.statusMessage = "Problem with the service.Please try again after sometime";
});
}

这是我的角度服务文件

CatchStockDetailHeader(stock: any)
: Observable<IStockCountHeaders[]> {
let IStockCounts = stock;  
console.log(IStockCounts)
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
headers.append('userid', IStockCounts.userid);
headers.append('created', IStockCounts.created);
headers.append('.CompanyID', IStockCounts.CompanyID);
headers.append('modified', IStockCounts.modified);
headers.append('modifieduserid', IStockCounts.modifieduserid);
headers.append('confirm', IStockCounts.confirm);    
return this._http.post('http://localhost:3071/api/Stockcountheader/' + 'Stock', IStockCounts, options)
.map((response: Response) => <IStockCountHeaders[]>response.json())
.catch(this.handleError);
}

您正在执行跨域请求,因为您正在发布到 localhost:3071,并且您通常在 localhost:4200 上托管 Angular 应用程序。

两个选项是从 api 添加允许所有标头或使用代理。

要允许来自您的 api 的跨域请求,请添加标头

Access-Control-Allow-Origin: *

在服务器上。

要使用代理,请创建一个名为 proxy.config.json 的文件

{
"/api/*": {
"target": "http://localhost:3071/api/",
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}

并与之一起服务

ng serve --proxy-config proxy.config.json

而不是使用

http://localhost:3071/api/

/api/

最新更新