[英]Angular 5+ consume data from asp.net core web api
I have a problem consuming data from an ASP.NET Core 2.0 Web API with Angular 5+. 我在使用来自Angular 5+的ASP.NET Core 2.0 Web API中的数据时遇到了问题。
Here the steps i have done: 我在这里完成的步骤:
Now the problem: I can make a request to the wep api from the frontend app and i am also recieveing the correct data in JSON-Format. 现在的问题是:我可以从前端应用程序向wep api发出请求,并且我还以JSON格式接收正确的数据。 But while the mapping process to the poco object in the generated client service class, something doesnt work.
但是,在生成的客户服务类中映射到poco对象的过程中,某些操作不起作用。 I always get an object with empty attributes.
我总是得到一个带有空属性的对象。
Here my code: 这是我的代码:
product.service.ts
export class ProductService {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: (key: string, value: any) => any = undefined;
constructor() {
this.http = <any>window;
this.baseUrl = "http://testweb01/FurnitureContractWebAPI";
}
getByProductId(productId: string): Promise<Product[]> {
let url_ = this.baseUrl + "/api/Product/GetById?";
if (productId === undefined)
throw new Error("The parameter 'productId' must be defined.");
else
url_ += "productId=" + encodeURIComponent("" + productId) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetByProductId(_response);
});
}
protected processGetByProductId(response: Response): Promise<Product[]> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
if (resultData200 && resultData200.constructor === Array) {
result200 = [];
for (let item of resultData200) {
var x = Product.fromJS(item);
//console.log(x);
result200.push(Product.fromJS(item));
}
}
//console.log(result200);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<Product[]>(<any>null);
}
And here the methods from the Product-class: 这里是Product类的方法:
init(data?: any) {
console.log(data);
if (data) {
this.productId = data["ProductId"];
this.productNameDe = data["ProductNameDe"];
this.productNameFr = data["ProductNameFr"];
this.productNameIt = data["ProductNameIt"];
this.supplierProductId = data["SupplierProductId"];
this.supplierProductVarId = data["SupplierProductVarId"];
this.supplierProductVarName = data["SupplierProductVarName"];
this.supplierId = data["SupplierId"];
this.supplierName = data["SupplierName"];
this.additionalText = data["AdditionalText"];
this.installationCost = data["InstallationCost"];
this.deliveryCost = data["DeliveryCost"];
this.sectionId = data["SectionId"];
this.categorieId = data["CategorieId"];
this.price = data["Price"];
this.ean = data["Ean"];
this.brand = data["Brand"];
this.modifiedDate = data["ModifiedDate"] ? new Date(data["ModifiedDate"].toString()) : <any>undefined;
this.categorie = data["Categorie"] ? ProductCategory.fromJS(data["Categorie"]) : <any>undefined;
this.section = data["Section"] ? ProductSection.fromJS(data["Section"]) : <any>undefined;
}
}
static fromJS(data: any): Product {
data = typeof data === 'object' ? data : {};
let result = new Product();
result.init(data);
return result;
}
In the init() method when i look at data , it contains all the values i need. 在查看数据的init()方法中,它包含我需要的所有值。 But when i for example use data["ProductId"] the value is null/undefined.
但是,例如当我使用data [“ ProductId”]时,该值为null / undefined。
Can anyone please help? 谁能帮忙吗?
Thanks 谢谢
Here is a screenshot of my console output of the data object: enter image description here 这是数据对象的控制台输出的屏幕快照: 在此处输入图像描述
Now I could figure out, that i can cast the data object directly to Product: 现在我可以弄清楚,我可以将数据对象直接转换为Product:
init(data?: any) {
var p = <Product>data;
This works, but i am asking myself, why does the generated class have an init-method with manually setting of the attributes, when it is possible to cast the object directly? 这可行,但是我问自己,为什么可以直接转换对象,为什么生成的类具有手动设置属性的初始化方法?
NSwag is misconfigured, use DefaultPropertyNameHandling: CamelCase for ASP.NET Core NSwag配置错误,请使用DefaultPropertyNameHandling:CamelCase for ASP.NET Core
Or use the new asp.net core api explorer based swagger generator which automatically detects the contract resolver. 或者使用新的基于asp.net核心api资源管理器的swagger生成器,该生成器会自动检测合同解析器。 (Experimental)
(实验性)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.