How to get a value on angular typescript in json - arrays

Here is my json respond using laravel spatie I created a respond that show if the user is have an Roles
{
"message": "Successfuly fetch all User",
"error": false,
"error_code": 200,
"line": "line 117 UserController.php",
"data": [
{
"id": 1,
"name": "dasdsa",
"email": "dasdsad#gmail.com",
"email_verified_at": null,
"created_at": "2020-04-22T13:37:41.000000Z",
"updated_at": "2020-04-22T13:37:41.000000Z",
"roles": [
{
"id": 2,
"name": "publisher",
"guard_name": "web",
"created_at": "2020-04-23T11:11:33.000000Z",
"updated_at": "2020-04-23T11:11:33.000000Z",
"pivot": {
"model_id": 1,
"role_id": 2,
"model_type": "App\\User"
}
}
]
},
{
"id": 2,
"name": "mdsadsadn",
"email": "dasdsad#gmail.coms",
"email_verified_at": null,
"created_at": "2020-04-23T10:37:10.000000Z",
"updated_at": "2020-04-23T12:04:46.000000Z",
"roles": [
{
"id": 2,
"name": "publisher",
"guard_name": "web",
"created_at": "2020-04-23T11:11:33.000000Z",
"updated_at": "2020-04-23T11:11:33.000000Z",
"pivot": {
"model_id": 2,
"role_id": 2,
"model_type": "App\\User"
}
}
]
}
]
}
and this is my code on angular 9.1.3 to get the value name in roles array
export class UserComponent implements OnInit {
roles:any;
result:any;
constructor(private _userService:UsersService) { }
ngOnInit(): void {
this.getallUser();
}
getallUser(){
this._userService.getallUsers().subscribe((event : HttpEvent<any>) => {
if (event.type === HttpEventType.Response) {
if (event.status == 200) {
let body = event.body;
let error = body.error;
let msg = body.message;
//alert(body);
// console.log(body.data);
if (!error) {
this.dataTbl.tblVal = body.data
this.roles = body.data.roles;
console.log(this.roles)
// this.result = this.roles.map(a => a.roles);
// console.log(this.result);
// console.log(this.dataTbl.tblVal)
}
}
}
this.dataTbl.tblLoad = false;
}, (err : HttpErrorResponse) => {
console.log(err);
});
}
}
Here is my service
import { Injectable } from '#angular/core';
import { HttpClient, HttpRequest, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private _httpClient: HttpClient) {
}
getallUsers() {
return this._httpClient.get("http://localhost:8000/api/getallUser", {
observe: 'response', reportProgress: true });
}
}
My problem is I want to get the value of name in roles example:publisher but i cannot access on that object how to get that value the error is undefined I dont know what's wrong with my code thank you for the help

Related

JSON dot notation returning different from JSON api request [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 14 days ago.
Using dot notation to access a JSON response is returning different values than what the API response is saying in my browser
I tried to access a JSON response from an axios request like so:
const response = await axios.get('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US');
console.log(response.data.data.Catalog.searchStore.elements.promotions)
Instead of getting a response something similar to this in JSON:
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-02T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
],
"upcomingPromotionalOffers": []
}
}
I simply get this from the console log:
undefined
undefined
undefined
undefined
undefined
I might not be using dot notation to access it correctly but I have no idea. You can view the JSON response from the browser here: https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US
#1 Getting data from the server by axios.
The elements start [ and end ] is an array data.
(* I copy/paste from Browser to VS code after access URL, saved JSON data)
VS code can expand/collapse data by clicking down arrow.
#2 Filter only promotions
It is one of Key values of array elements
You can filter by Array map()
Simple example for getting title only
const titles = elements.map(item => { return { title : item.title } } )
console.log(JSON.stringify(titles, null, 4))
[
{
"title": "Borderlands 3 Season Pass"
},
{
"title": "City of Gangsters"
},
{
"title": "Recipe for Disaster"
},
{
"title": "Dishonored®: Death of the Outsider™"
},
{
"title": "Dishonored - Definitive Edition"
}
]
So this code will works for getting promotions
const axios = require('axios')
const getPromotions = async (data) => {
try {
const response = await axios.get('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US');
return Promise.resolve(response.data)
} catch (error) {
return Promise.reject(error)
}
};
getPromotions()
.then(result => {
const promotions = result.data.Catalog.searchStore.elements.map(item => { return { promotions : item.promotions } } )
console.log(JSON.stringify(promotions, null, 4))
})
.catch(error => {
console.log(error.message)
});
Result
$ node get-data.js
[
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-01-26T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 30
}
},
{
"startDate": "2023-01-26T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 30
}
}
]
}
],
"upcomingPromotionalOffers": []
}
},
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-02T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
],
"upcomingPromotionalOffers": []
}
},
{
"promotions": {
"promotionalOffers": [],
"upcomingPromotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-09T16:00:00.000Z",
"endDate": "2023-02-16T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
]
}
},
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-02T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
],
"upcomingPromotionalOffers": []
}
},
{
"promotions": null
}
]

Remove object from array with mongoose 5.12 ($pull not working)

I have a problem with mongoose 5.12.
{
"_id": {
"$oid": "60db70c9956a6c4d0645d447"
},
"articles": [
{
"_id": {
"$oid": "60db8764da322a23e787ca3d"
},
"type": "Déssert",
"name": "dfd",
"description": "",
"price": 0,
"tag": "",
"picture": "noarticle.jpg"
},
],
"editor": 27,
}
My restaurant document contains articles (object array)
And I want to remove an article from it.
I'm using this:
const deletedArticle = await this.restaurantModel.findOneAndUpdate(
{ editor: userId },
{ $pull: { articles: articleId } },
{ multi: true, new: true, useFindAndModify: true },
);
// userId -> 27 and articleId --> "60db8764da322a23e787ca3d"
But nothing changes.
Is this an _id type problem? Or anything else?
(The $push option work)
You did wrong in the line:
{ $pull: { articles: articleId } }
It should be:
{ $pull: { articles: { _id : articleId } } }
Or:
{ $pull: {"articles._id" : articleId } }

hotchocolate: How to raise multiple errors in Errors[] array

Is it possible to raise multiple errors in Errors[] array, like hotchocolate does when you try to use unknow properties ?
If yes, how can I do this ?
My use case is to return errors collection when validating an object with Validator.TryValidateObject
See below what hotchocolate returns when fields are unknow.
I would like to do the same : multiple elements in Errors[] array.
{
"Label": null,
"Path": null,
"Data": null,
"Errors": [
{
"Message": "The field `date` does not exist on the type `EcritureConnection`.",
"Code": null,
"Path": {
"Parent": null,
"Depth": 0,
"Name": "ecritures"
},
"Locations": [
{
"Line": 1,
"Column": 75
}
],
"Extensions": {
"type": "EcritureConnection",
"field": "date",
"responseName": "date",
"specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
},
"Exception": null
},
{
"Message": "The field `intitule` does not exist on the type `EcritureConnection`.",
"Code": null,
"Path": {
"Parent": null,
"Depth": 0,
"Name": "ecritures"
},
"Locations": [
{
"Line": 1,
"Column": 80
}
],
"Extensions": {
"type": "EcritureConnection",
"field": "intitule",
"responseName": "intitule",
"specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
},
"Exception": null
}
],
"Extensions": null,
"ContextData": {
"HotChocolate.Execution.ValidationErrors": true
},
"HasNext": null
}
There are multiple ways of setting errors in HotChocolate
How to build errors
Both ways require you to create a IError object.
You can use the ErrorBuilder to build this error. You do not need to set all of the fields, but the more the better the error does look:
ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.SetException(ex)
.AddLocation(context.Selection.SyntaxNode)
.SetPath(context.Path)
.Build()
This would generate this error in the response:
{
"errors": [
{
"message": "This is the message",
"locations": [
{
"line": 3,
"column": 21
}
],
"path": [
"hello"
],
"extensions": {
"code": "YOURCODE00000123"
}
}
],
"data": {
"hello": "World"
}
}
How to raise errors
You can report errors on the IResolverContext or the IMiddlewareContext
Annotation Based
public class Query
{
public string Hello(IResolverContext context)
{
context.ReportError(
ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.AddLocation(context.Selection.SyntaxNode)
.SetPath(context.Path)
.Build());
return "World";
}
}
Code First
public class QueryType : ObjectType<Query>
{
protected override void Configure(IObjectTypeDescriptor<Query> descriptor)
{
descriptor.Field(x => x.Hello)
.Resolver(context =>
{
context.ReportError(
ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.AddLocation(context.Selection.SyntaxNode)
.SetPath(context.Path)
.Build());
return "World";
});
}
}
By throwing a GraphQlException
public class Query
{
public string Hello()
{
var error1 = ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.Build();
var error2 = ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.Build();
throw new GraphQLException(error1, error2)
}
}

How do I sort this array by date?

I'm trying to sort the dates from this external API in my latestResults array by latest on top to oldest on bottom but can't seem to figure out how.
Right now they're displayed with the oldest date first and it's working fine, but it's in the wrong order for me.
I tried using result in latestResults.reverse() but that just reverses the 7 items currently in the array.
HTML:
<div v-for="result in latestResults" v-bind:key="result.latestResults">
<small">{{ result.utcDate }}</small>
</div>
Script:
<script>
import api from '../api'
export default {
data () {
return {
latestResults: [],
limit: 7,
busy: false,
loader: false,
}
},
methods: {
loadMore() {
this.loader = true;
this.busy = true;
api.get('competitions/PL/matches?status=FINISHED')
.then(response => { const append = response.data.matches.slice(
this.latestResults.length,
this.latestResults.length + this.limit,
this.latestResults.sort((b, a) => {
return new Date(b.utcDate) - new Date(a.utcDate);
})
);
setTimeout(() => {
this.latestResults = this.latestResults.concat(append);
this.busy = false;
this.loader = false;
}, 500);
});
}
},
created() {
this.loadMore();
}
}
</script>
The JSON where I'm getting matches like this that has utcDate:
{
"count": 205,
"filters": {
"status": [
"FINISHED"
]
},
"competition": {
"id": 2021,
"area": {
"id": 2072,
"name": "England"
},
"name": "Premier League",
"code": "PL",
"plan": "TIER_ONE",
"lastUpdated": "2021-02-01T16:20:10Z"
},
"matches": [
{
"id": 303759,
"season": {
"id": 619,
"startDate": "2020-09-12",
"endDate": "2021-05-23",
"currentMatchday": 22
},
"utcDate": "2020-09-12T11:30:00Z",
"status": "FINISHED",
"matchday": 1,
"stage": "REGULAR_SEASON",
"group": "Regular Season",
"lastUpdated": "2020-09-13T00:08:13Z",
"odds": {
"msg": "Activate Odds-Package in User-Panel to retrieve odds."
},
},

How to fetch data from json in angularjs Form

How to call the data from json in angularjs form without using backend. i have written this code and here m unable to find a way in last to get data from the json file. someone please help me to move forward from here.
code
$scope.count = $scope.newPreAuth.length;
};
//Delete newPreAuth - Using AngularJS splice to remove the preAuth row from the newPreAuth list
//All the Update newPreAuth to update the locally stored newPreAuth List
//Update the Count
$scope.deletenewPreAuth = function (preAuth) {
$scope.newPreAuth.splice($scope.newPreAuth.indexOf(preAuth), 1);
getLocalStorage.updatenewPreAuth($scope.newPreAuth);
$scope.count = $scope.newPreAuth.length;
};
}]);
//Create the Storage Service Module
//Create getLocalStorage service to access UpdateEmployees and getEmployees method
var storageService = angular.module('storageService', []);
storageService.factory('getLocalStorage', function () {
var newPreAuthList = {};
return {
list: newPreAuthList,
updatenewPreAuth: function (newPreAuthArr) {
if (window.localStorage && newPreAuthArr) {
//Local Storage to add Data
localStorage.setItem("newPreAuth", angular.toJson(newPreAuthArr));
}
newPreAuthList = newPreAuthArr;
},
getnewPreAuth: function () {
//Get data from Local Storage
newPreAuthList = angular.fromJson(localStorage.getItem("newPreAuth"));
return newPreAuthList ? newPreAuthList : [];
}
};
});
Json Code
PreAuth:
======================
URL:http://dev.xxx.com:8080/xxx/preAuth
TYPE:POST
X-Auth-Token t3Z10HGEiYFdzq9lGtr18ycdeAAXmWBEI64rQAJcAte6Ka8Tz96IAhuXHSgpiKufsd
{
"preAuth": {
"claimbId": "newPreAuth",
"claimbStatus": "new",
"patientInfo": {
"patientName": "name",
"gender": "Male",
"dob": 950639400000,
"age": 21,
"contactNumber": 9987654356,
"tpaMemberId": 950639400121,
"policyNumber": "ABC12615627",
"corporateName": "ABC",
"EmployeeId": "XYZ10232",
"otherInsurance": {
"isOtherInsurance": true,
"playerName": "xyx",
"details": "sdfdsafdsfdsf"
},
"familyPhysician": {
"isFamilyPhysician": true,
"physicianName": "fsdf"'c
"physicianContactNumber": 7878748728,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"isFamilyPhysician": false,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"medicalInfo": {
"illnessType": "cancer",
"clinicalFinding": "description",
"ailmentDuration": "2 months",
"ailmentHistory": "description",
"illnessCause": "alcohol",
"provisionalDiagnosis": [
{
"diagnosisName": "abc",
"diagnosisICDCode": "121423"
},
{
"diagnosisName": "xyz",
"diagnosisICDCode": "434543"
}
],
"differentialDiagnosis": [
{
"diagnosisName": "afasdbc",
"diagnosisICDCode": "12431423"
},
{
"diagnosisName": "fdxyz",
"diagnosisICDCode": "434sdf543"
}
],
"clinicalObservations": {
"BP": "120/80",
"CVS": "126",
"P.A.": "abc",
"R.S.": "aa",
"CNS": "dd",
"others": "others"
},
"maternityDetails": {
"maternityType": "G",
"L.M.P.": 950639400000,
"E.D.D.": 950639400000
},
"accidentDetails": {
"accidentCause": "xyz",
"accidentDate": 950639400000,
"isPoliceComplaint": true,
"firNumber": "asfsafds"
},
"pastIllness": [
{
"pastIllnessType": "Diabetes",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Hypertension",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Other",
"isPresent": false,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
}
]
},
"treatmentInfo": {},
"billingInfo": {},
"documents": [
{
"documentId": 12345,
"documentMetadata": {
"documentName": "discharge summary",
"date": 950639400000,
"version": "1.1",
"viewedStatus": false,
"link": "link to view/download document"
}
},
{
"documentId": 12346,
"documentMetadata": {
"documentName": "medical summary",
"date": 950639400000,
"version": "1.0",
"viewedStatus": true,
"link": "link to view/download document"
}
}
]
}
}
I created sample ,it worked this way
// Code goes here
var app = angular.module('app',[]);
app.controller('sample', function($scope,$http){
$scope.name = "advaitha";
$http.get('test.json').then(function(data){
console.log(data.data);
});
})
here is the plunker example
using HTML5 localStorage would require you to serialize and deserialize your objects before using or saving them.
For example:
var myObj = {
firstname: "kisun",
lastname: "rajot",
website: "https://www.kisun.com"
}
//if you wanted to save into localStorage, serialize it
window.localStorage.set("empData", JSON.stringify(myObj));
//unserialize to get object
var myObj = JSON.parse(window.localStorage.get("empData"));
Created a plunker based on your code am able save and retrieve the json data with your code. Please check here

Resources