Pass JSON Object with REST - json

I have a rest-api-service with the following call to a REST method that returns a very complex JSON object in the body of its response. This code is from the rest-api-service.ts file.
getLocalObjectsFromREST(): Observable<LocalObjects> {
return this.http.get<LocalObjects>(this.apiURL + '/api/GetLocalObjects')
.pipe(
retry(1),
catchError(this.handleError)
)
}
handleError(error: { error: { message: string; }; status: any; message: any; }) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
I am attempting to grab that response in a component with the following that is in my app.component.ts file:
export class AppComponent implements OnInit {
_restApi: RestApiService | undefined;
_localObjects: LocalObjects | undefined;
contructor(restApi: RestApiService) {
this._restApi = restApi;
}
ngOnInit() {
this.getLocalObjectsFromService();
console.log("Main object has a name of: " + this._localObjects?.mainObject.objName)
console.log("Data Returned is " + this._localObjects);
}
getLocalObjectsFromService() {
return this._restApi?.getLocalObjectsFromREST().subscribe((data: {}) => {
this._localObjects = <LocalObjects> data;
})
}
}
I am receiving no errors and yet the console logs are showing undefined return values.
Can somebody please help me out?

ngOnInit() {
this.getLocalObjectsFromREST();
console.log("Main object has a name of: " + this._localObjects?.mainObject.objName)
console.log("Data Returned is " + this._localObjects);
}
getLocalObjectsFromService() {
return this._restApi?.getLocalObjectsFromREST().subscribe((data: {}) => {
this._localObjects = <LocalObjects> data;
})
}
In your ngOnInit() you are not calling your getLocalObjectsFromService() function and as you are not adding a subscribe() after getLocalObjectsFromREST you are not seeing any data...

Related

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);

Object from Observable then Array from Observable inside a foreach. how to order it?Asynchronous Angular 4/5

Here is my problem.
I'm running a method that sends me a json (method = myTableService.getAllTables ()), to create an object (object = this.myTables).
Then I execute the method for each, for each element of this.myTables I execute a new request (request = this.myTableService.getTableStatut (element.theId)).
I retrieve data from a new json to create an object (object = myTableModel).
Each result will be added to this.myTableListProvisory.
The problem is the order of execution.
It execute the console.log before the end of the for each...
This.myTableListProvisory.length and this.myTableList.length return 0.
How to wait for the end of the for each run before running the console.log?
Thank you
ngOnInit() {
this.myTableService.getAllTables()
.subscribe(data => {
this.myTables = data;
this.myTableList = this.getAllTableStatut(this.myTables);
console.log("this.myTableList.length : " + this.myTableList.length);
}, err => {
console.log(err);
})
}
getAllTableStatut(myTables: any) {
this.myTableListProvisoire = [];
myTables.forEach(element => {
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
})
console.log("this.myTableListProvisoire.length : " + this.myTableListProvisoire.length);
})
return this.myTableListProvisoire;
}
Result of console.log
this.myTableListProvisoire.length : 0
this.myTableList.length : 0
UPDATE
I have simplified the code ... I put it in its entirety for the understanding. What I need is to sort the array after it is done. The problem is that I don't know how to use a flatMap method in a query inside a foreach ... I have temporarily placed the sort method inside the subscribe which is a bad solution for the performance. That's why I want to do my sort after the creation of the array. Thank you
export class MyTableComponent implements OnInit {
myTables: any;
statut: any;
myTableModel: MyTableModel;
myTableList: Array<MyTableModel>;
myTableListProvisoire: Array<MyTableModel>;
i: number;
j: number;
myTableModelProvisoire: MyTableModel = null;
constructor(public myTableService: MyTableService) { }
ngOnInit() {
this.myTableService.getAllTables()
.subscribe(data => {
this.myTables = data;
this.myTableList = this.getAllTableStatut(this.myTables);
}, err => {
console.log(err);
})
}
getAllTableStatut(myTables: any) {
this.myTableListProvisoire = [];
myTables.forEach(element => {
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
for (this.j = 0; this.j < this.myTableListProvisoire.length; this.j++) {
for (this.i = 0; this.i < this.myTableListProvisoire.length - 1; this.i++) {
if (this.myTableListProvisoire[this.i].getTableNumber() > this.myTableListProvisoire[(this.i + 1)].getTableNumber()) {
this.myTableModelProvisoire = this.myTableListProvisoire[this.i];
this.myTableListProvisoire[this.i] = this.myTableListProvisoire[(this.i + 1)];
this.myTableListProvisoire[(this.i + 1)] = this.myTableModelProvisoire;
}
}
}
}, err => {
console.log(err);
})
}, err => {
console.log(err);
})
return this.myTableListProvisoire;
}
}
Well Observables are asynchronous actions and will be executed after finishing the current execution block. So when the js engine comes to your
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
})
it will only create a subscription, but the code inside of it will be executed after all the other code in the block. So that's why your console.log is being executed before you get any data. So you need to place it inside the .subscribe block to see the. I think there can be a better solution to get the data, but I don't know the structure of the app, so I can't advice. If you create an example on https://stackblitz.com/ I could probably help you out with a better solution.

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

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);
});
}

Delete row data from Firebase

I want to delete one clicked row from Firebase in my smart table. I am using Angular 4.
The smart table code:
<ng2-smart-table [settings]="settings" [source]="bicycleData"
(deleteConfirm)="onDeleteConfirm($event)">
</ng2-smart-table>
My constructor component code:
constructor(
db: AngularFireDatabase, ) {
this.bicyclesList = db.list('bicycle-list')
.snapshotChanges()
.map(changes => {
return changes.map(c => ({
key: c.payload.key,
...c.payload.val()
}))
});
this.bicyclesList.subscribe((data) => {
this.bicycleData = data;
});
}
and component.ts code:
settings = {
delete : {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
}
onDeleteConfirm() function and deleteEnquiry function in service:
onDeleteConfirm(event) {
console.log(event.data);
if (window.confirm('Are you sure you want to delete?')) {
this.deleteEnquiry(event.data);
event.confirm.resolve();
} else {
event.confirm.reject();
}
}
deleteEnquiry(data) {
console.log(data.$key);
this.db.list(`bicycle-list${data.$key}`).remove(data);
}
But it keeps showing me the following error in console:
ERROR TypeError: Cannot read property 'list' of undefined
How can I fix this error ?
Looks like an error in deleteEnquiry.
According to the docs is should be:
deleteEnquiry(data) {
console.log(data.$key);
this.db.list('bicycle-list').remove(data.$key);
}

Typescript converting a JSON object to Typescript class

Hello I am attempting to change an array of JSON objects to a TypeScript class. However the method seems to crash every I attempt to assign a Json object attribute to a typescript attribute.
Typescript interface
export interface marker {
lat: number;
lng: number;
}
Typescript method
public markers: marker[];
ngOnInit() {
this.mapService.GetPhotosById(this.id).subscribe(resultlisting => {
this.values = resultlisting;
console.log(this.values); //SHOW IN PICTURE
this.ChangetoMarkers(this.values);
}, error => this.errorMessage = error);
}
ChangetoMarkers(someArray: Observable<any[]>) {
for (let entry of someArray) {
let mark: marker;
mark.lat = Number(entry.latitude); //Attempt to convert to number
mark.lng = +entry.longitude; //2nd attempt to convert to number
this.markers.push(mark);
};
console.log(this.markers); //DOES NOT REACH THIS
}
Map Service
GetPhotosById(id: string): Observable<any> {
return this.http
.post(this.config.apiEndpoint + "mapPhotos/" + id)
.map(this.extractJson).catch(this.handleErrors);
};
private extractJson(res: Response) {
let data = res.json();
return data;
}
private handleErrors(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.log(errMsg);
return Observable.throw(errMsg);
}
I have researched the issue and have attempted to apply the interger cast but it does not seem to work. Any suggestions would be great.
As  Mauricio Poppe noted in his comment, you are trying to access the properties of a variable that has no value.
changeToMarkers(points: Array<{latitude: number, longitude: number}>) {
this.markers = entries.map(({latitude: lat, longitude: lng}) => ({
lat,
lng
}));
console.log(this.markers);
}
No number conversions are necessary because the deserialized representations of latitude and longitude are already compatible numeric values.
Try this:
ChangetoMarkers(someArray: any[]) {
console.log("array",someArray);
for (let entry of someArray) {
let mark: marker = {lat: entry.latitude, lng: entry.longitude};
console.log("mark", mark);
this.markers.push(mark);
};
console.log("markers",this.markers);
}
It isn't as elegant as Aluan Haddad's, but it should allow you to determine at which point it is breaking if for some reason this still doesn't work, by logging someArray before the loop, the marks before being pushed, and this.markers after to determine exactly where the problem is breaking down.