Why isn't my function returning the proper JSON data and how can I access it? - json

I'm running services to retrieve data from an API. Here is one of the services:
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token;
const myObject: any = {core_id : core_id, channel_name: channel_name};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/',options)
.subscribe(
res => console.log(res),
)
}
}
The data shows up properly on the console, but I still can't access the individual keys:
Here is how I call it:
ngOnInit(): void{
this.login.getData(this.username, this.password).subscribe((data) => {
this.robotSummaryData = this.getRobotSummary.robotSummary(this.core_id, this.channel_name);
console.log("robosummary"+ this.robotSummaryData)
});
}
When I call this function and assign it to a variable, it shows up on console as [object Object]. When I tried to use JSON.parse, it throws the error: type subscription is not assignable to parameter string. How can I access the data? I want to take the JSON object and save it as an Object with appropriate attributes. Thanks!

Do not subscribe inside your service, do subscribe in your component, change your service as follows,
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token; const myObject: any = { core_id: core_id, channel_name: channel_name };
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/', options)
.map((response: Response) => response);
}
and then in your component,
ngOnInit(){
this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
this.data = data;
console.log(this.data);
});
}

Related

Autodesk.DesignAutomation returning Unexpected token S in JSON at position 0 when calling the workitem api

I am facing a new issue with a fetch
handleSendToForge(e) {
e.preventDefault();
let formData = new FormData();
formData.append('data', JSON.stringify({
Width: this.state.Width,
Length: this.state.Length,
Depth: this.state.Depth,
Thickness: this.state.Thickness,
BottomThickness: this.state.BottomThickness,
rebarSpacing: this.state.rebarSpacing,
outputrvt: this.state.outputrvt,
bucketId: this.state.bucketId,
activityId: 'RVTDrainageWebappActivity',
objectId: 'template.rvt'
}));
this.setState({
form: formData
})
fetch('designautomation', {
method: 'POST',
body: formData,
//headers: {
// //'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
//},
})
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log(error));
}
and the code for the controller is pretty standard and is slightly modified from one of the forge examples
[HttpPost]
[Route("designautomation")]
public async Task<IActionResult> Test([FromForm] StartWorkitemInput input)
{
JObject workItemData = JObject.Parse(input.data);
double Width = workItemData["Width"].Value<double>();
double Length = workItemData["Length"].Value<double>();
double Depth = workItemData["Depth"].Value<double>();
double Thickness = workItemData["Thickness"].Value<double>();
double BottomThickness = workItemData["BottomThickness"].Value<double>();
double rebarSpacing = workItemData["rebarSpacing"].Value<double>();
string outputrvt = workItemData["outputrvt"].Value<string>();
string activityId = workItemData["activityId"].Value<string>();
string bucketId = workItemData["bucketId"].Value<string>();
string objectId = workItemData["objectId"].Value<string>();
// basic input validation
string activityName = string.Format("{0}.{1}", NickName, activityId);
string bucketKey = bucketId;
string inputFileNameOSS = objectId;
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// prepare workitem arguments
// 1. input file
dynamic inputJson = new JObject();
inputJson.Width = Width;
inputJson.Length = Length;
inputJson.Depth = Depth;
inputJson.Thickness = Thickness;
inputJson.BottomThickness = BottomThickness;
inputJson.rebarSpacing = rebarSpacing;
inputJson.outputrvt = outputrvt;
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/aecom-bucket-demo-library/objects/{0}", objectId),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 2. input json
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
},
Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
};
// 3. output file
string outputFileNameOSS = outputrvt;
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
// the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
//string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&bucketKey={2}&outputFileName={3}", OAuthController.FORGE_WEBHOOK_URL, browerConnectionId, bucketKey, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "rvtFile", inputFileArgument },
{ "jsonFile", inputJsonArgument },
{ "result", outputFileArgument }
///{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
DesignAutomationClient client = new DesignAutomationClient();
client.Service.Client.BaseAddress = new Uri(#"http://localhost:3000");
WorkItemStatus workItemStatus = await client.CreateWorkItemAsync(workItemSpec);
return Ok();
}
Any idea why is giving me this error? I have tested the api using postman and it works fine but when I try to call that from a button I keep receive this error. Starting the debug it seems that the url is written correctly. Maybe it is a very simple thing that i am missing.
Cheers!
OK solved...
I was missing to add the service in the Startup and also the Forge connection information (clientid, clientsecret) in the appsettings.json
Now I need to test the AWS deployment and I guess I am done!

Json string array to object in Vuex

In my states I have categories. In the categories array every each category have a settings column where I have saved json array string.
My question it is,how can I turn my string to object by filtering the response ?
My response:
[{"id":4,"name":"Vehicles","slug":"vehicles","settings":"[{"edit":true,"searchable":true}]","created_at":"2019-01-26 16:37:36","updated_at":"2019-01-26 16:37:36"},
This is my loading action for the categories:
const loadCategories = async ({ commit }, payload) => {
commit('SET_LOADING', true);
try {
const response = await axios.get(`admin/store/categories?page=${payload.page}`);
const checkErrors = checkResponse(response);
if (checkErrors) {
commit('SET_DIALOG_MESSAGE', checkErrors.message, { root: true });
} else {
commit('SET_STORE_CATEGORIES', response.data);
}
} catch (e) {
commit('SET_DIALOG_MESSAGE', 'errors.generic_error', { root: true });
} finally {
commit('SET_LOADING', false);
}
};
This is my SET_STORE_CATEGORIES:
const SET_STORE_CATEGORIES = (state, payload) => {
state.categories=payload.data;
state.pagination = {
currentPage: payload.current_page,
perPage: payload.per_page,
totalCategories: payload.total,
totalPages: payload.last_page,
};
};
Here I would like to add to modify the value ,to turn the string to object.
Had to add:
let parsed=[];
parsed=response.data.data.map((item)=>{
console.log(item);
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
response.data.data=parsed;
commit('SET_STORE_CATEGORIES', response.data);
You could map your response data as follows by parsing that string to an object :
let parsed=[];
parsed=response.data.map((item)=>{
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
commit('SET_STORE_CATEGORIES', parsed);

JSON data is shown as promise

my vue js code
export const store = new Vuex.Store({
state: {},
getters: {
changeempdatas: (state) => {
var apidata =Vue.axios.post ('http://127.0.0.1:5000/').then( (response) => {
return response.data
});
var changeempdatas = apidata.then(function(result) {
console.log(result.empdata)
return result.empdata;
})
console.log(changeempdatas)
return changeempdatas;
}
}
});
and my python code
conn= pymysql.connect
(host='127.0.0.1',user='root',password='',
db='test')
class senddata(Resource):
def post(self):
curr = conn.cursor()
getdataqry = curr.execute("SELECT *
FROM `employee`")
getdatas = curr.fetchall()
#empdata = []
print "Post"
i=0
empdata = {}
for getdata in getdatas:
i += 1
empdata[i] = {}
empdata[i]['id'] = getdata[0]
empdata[i]['name'] = getdata[1]
#empdata.append({'id': getdata[0],
'name': getdata[1]})
return jsonify({'empdata': empdata})
a.close()
The JSON data from python is not received as JSON, It shows as a promise. How can I call the JSON data as normal JSON?
response output

Casting Response from HTTP Post to List of Typescript Objects

I have a call to my web API already written. The API returns a list of objects serialized in JSON. I know that there are fairly reasonable ways to cast individual items from JSON to typescript objects, but I cant figure out a way to do this casting to make it return a list of a typescript object.
I need to cast to a typescript object as there is a function in the object I want to be able to run, but without casting the function does not exist.
Here is the code used to retrieve the JSON:
findTrainPage(filter = '', sortOrder = 'desc', pageNumber = 0, pageSize = 15, departStart=null, departEnd=null, origStatusWhitelist=null): Observable<Train[]>
{
//retrieves a page of trains to display in the train list
let url = AppUtils.backendApiUrl() + '/trainList/getPage';
let requestBody = { 'filter': filter, 'sortOrder': sortOrder, 'pageNum': pageNumber, 'pageSize': pageSize, 'departStart': departStart, 'departEnd': departEnd, 'origStatusWhitelist': origStatusWhitelist };
let options = new RequestOptions({ headers: AppUtils.commonHttpHeaders() });
let headers = { headers: AppUtils.commonHttpHeaders() };
return this.http.post(url, requestBody, headers).map(res => res.json()).catch(error => Observable.throw(error.json()));
}
And here is the Train object I am trying to cast to:
export class Train implements TrainInterface
{
trainGUID: string;
trainSymbol: string;
createTime: string; //Should be formatted as a date, SQL table uses smalldatetime
departTime: string;
origStatus: OriginalStatuses;
badGUIDFlag: boolean;
trips: Trip[];
private _evalStatus: EvalStatuses;
get evalStatus(): EvalStatuses
{
return this.trips.reduce((min, p) => p.evalStatus < min ? p.evalStatus : min, this.trips[0].evalStatus);
}
}
I have looked at the following SO posts:
JSON to TypeScript class instance?
Angular2 HTTP GET - Cast response into full object
Create a response wrapper class. This should match with the API response structure.
export declare class ResponseWrapper<T> {
static SUCCESS: number;
data: Array<T>;
}
Then map the response as follows.
findTrainPage(filter = '', sortOrder = 'desc', pageNumber = 0, pageSize = 15, departStart = null, departEnd = null, origStatusWhitelist = null): Observable<any> {
//retrieves a page of trains to display in the train list
// let url = AppUtils.backendApiUrl() + '/trainList/getPage';
const url = 'assets/mockdata.json';
let requestBody = {
'filter': filter,
'sortOrder': sortOrder,
'pageNum': pageNumber,
'pageSize': pageSize,
'departStart': departStart,
'departEnd': departEnd,
'origStatusWhitelist': origStatusWhitelist
};
let options = new RequestOptions();
return this.http.get(url)
.map(res => res.json())
.catch(error => Observable.throw(error.json()));
}
Usage :
trainList : Train[];
constructor(private trainService: TrainService) {
this.trainService.findTrainPage()
.subscribe(data =>{
const resultsWrapper:ResponseWrapper<Train> = data;
this.trainList = resultsWrapper.data;
});
// error => this.errorMessage = error);
}
Here is the tested source https://gitlab.com/supun/angular-stack-overflow-ref

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+.
Here the steps i have done:
I have built an ASP.NET Core 2.0 WebAPI and deployed it on a server. I can consume data from postman or swagger without any problems.
Then i have created with NSwagStudio the client TypeScript service classes for my angular frontend app.
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.
But while the mapping process to the poco object in the generated client service class, something doesnt work. 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:
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. But when i for example use data["ProductId"] the value is 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:
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
Or use the new asp.net core api explorer based swagger generator which automatically detects the contract resolver. (Experimental)