Lightning Web Component to display JSON String is not working - javascript

I have the following lightning web component to read a JSON string and display them in Contact record Details page. Please note that I am new to lighting web components and making a considerable amount of effort to learn.
MyComponent.html
<template>
<lightning-record-form
object-api-name={contactObject}
fields={myFields}
onsuccess={handleContactCreated} onload={handleContactInitialized} >
</lightning-record-form>
</template>
MyComponent.js
import { LightningElement, wire, track } from 'lwc';
import findDetails from
'#salesforce/apex/JSONDemoController.getContactWithRelatedDataById';
import CONTACT_OBJECT from '#salesforce/schema/Contact';
import NAME_FIELD from '#salesforce/schema/Contact.Name';
import TEST_FIELD from '#salesforce/schema/Contact.TestField__c';
import SPOUSE_FIELD from '#salesforce/apex/ResponseJSONWrapper.spouse';
import ADDRESS_FIELD from
'#salesforce/apex/ResponseJSONWrapper.mailingAddress';
export default class ContactCreator extends LightningElement {
contactObject = CONTACT_OBJECT;
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
#track contacts;
#track error;
handleContactCreated(){
// Run code when account is created.
}
handleContactInitialized(){
findDetails()
.then(result => {
var responseObj = JSON.parse(result.getReturnValue());
this.SPOUSE_FIELD = responseObj.spouse;
this.ADDRESS_FIELD = responseObj.mailingAddress;
})
.catch(error => {
this.error = error;
});
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
}
}
JSONDemoController.cls
public class JSONDemoController {
#AuraEnabled
public static String getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
response = JSON.serialize(wrapper);
return response;
}
}
ResponseJSONWrapper.cls
public with sharing class ResponseJSONWrapper {
public String spouse;
public String contactRecordType;
public Date birthDate;
public String mobile;
public String mailingAddress;
public String otherAddress;
public String languages;
public String level;
public String Description;
}
But I don't get the values I have hard coded in the lightning component when it is rendered. Nothing is there it's empty.
Can someone help to point out where I am going wrong ?

Change this line:
var responseObj = JSON.parse(result.getReturnValue());
To:
var responseObj = JSON.parse(result);
getReturnValue() is for Aura components.

You don't actually need to serialize the wrapper in apex and then parse in the component explicitly, the framework does the job by itself!
public class JSONDemoController {
#AuraEnabled //change return type to ResponseJSONWrapper
public static ResponseJSONWrapper getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
return wrapper; //return the wrapper itself
}
and in .js file
findDetails()
.then(result => {
var responseObj = result;
...
})
This way the code will be less cluttered with not-needed code :)

Related

ReplaySubject it is not updating the array when new object is added Angular

I am dealing with an error which when I try to create new page Object, it send to backend but it is not updating the array, I need to reload the page to see the all the array.
I am using Observable within async in the frontend.
I tried to console.log the ngOnInit of the page.component.ts but when I add new page and navigate to pages then the ngOnInit it isn't calling.
On Create new page it happens this.
It sends me to the route of pages where there I show all the list of pages.
But when I create new Page it is returningback an error which says.
ERROR Error: Error trying to diff 'Here is the name of the object'. Only arrays and iterables are allowed.
Update: as Marco said this happens because I mix page as Object instead I am iterating through array
But I am unable to resolve it and i need your help.
In the page.service.ts at pageModel when I add new Object it is returning me only the added Object not the whole array and there is the problem I think, but I don't know how to fix.
But If I reload page then I see all my Array.
This is my updated code.
This is my code.
export class PagesService {
public baseUrl = environment.backend;
private data = new ReplaySubject<any>();
public userID = this.authService.userID;
public editDataDetails: any = [];
public subject = new Subject<any>();
private messageSource = new BehaviorSubject(this.editDataDetails);
getPageID = this.messageSource.asObservable();
constructor(private http: HttpClient, private authService: AuthService) { }
public getPages() {
return this.http.get<any>(`${this.baseUrl}/pages/${this.userID}`).subscribe(res => this.data.next(res));
}
public pageModel(): Observable<Page[]> {
return this.data.asObservable(); // Here it throws error
}
public getPage(id): Observable<any> {
return this.http.get(`${this.baseUrl}/page/${id}`);
}
public setPage(page: Page, id: string) {
const api = `${this.baseUrl}/page`;
const user_id = id;
this.http.post<any>(api, page, {
headers: { user_id }
}).subscribe(res => this.data.next(res));
}
changeMessage(message: string) {
this.messageSource.next(message)
}
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe(res => this.data.next(res.data));
}
Updated Code from Answer.
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe(res => {
this.lastSetOfData = res;
this.data.next(this.lastSetOfData);
});
}
}
export class Page {
_id = "";
name = "";
slogan = "";
description = "";
url = "";
telephone: number;
pageUrl: string;
website: string;
founded: number;
organization: number;
email: string;
coverImage: string;
profileImage: string;
specialty?: Specialty[];
branches: Branches[];
locations?: Location[];
phone?:Phone;
userRole?: string;
roles?: Roles[];
}
export class Roles {
role= "";
userID = "";
}
This is the HTML of page.component .
<div class="main" *ngIf="!showWeb">
<div *ngFor="let page of pages$ | async" class="card width-900">
<app-pages-list class="d-flex width-900" [page]="page" [details]="'details'"></app-pages-list>
</div>
<div>
</div>
</div>
This is the TS file.
public pages$: Observable<Page[]>;
ngOnInit(): void {
this.pageService.getPages();
this.pages$ = this.pageService.pageModel();
}
And this is the code when I create new Page.
export class CreatePageComponent implements OnInit {
public page = new Page();
search;
public branch = [];
constructor(public router: Router,
public branchesService: BranchesService,
public authService: AuthService,
public pageService: PagesService,
public shareData: SenderService) { }
ngOnInit(): void {
}
createPage() {
this.page.url = this.page.name;
this.page.branches = this.branch;
this.page.locations = [];
this.page.specialty = [];
this.page.roles = [];
this.page.phone = this.page.phone;
this.page.pageUrl = `${this.page.name.replace(/\s/g, "")}${"-Page"}${Math.floor(Math.random() * 1000000000)}`;
this.pageService.setPage(this.page, this.authService.userID);
}
addBranch(event) {
this.branch.push(event);
this.search = "";
}
removeBranch(index) {
this.branch.splice(index, 1);
}
}
From my understanding of your code, your error is thrown because the data variable hold 2 types of objects.
In the PagesServices:
In getPages you give data a list of Page.
In setPage and updatePage you give data an instance of Page.
private data = new ReplaySubject<any>();
When you create a new page, data hold the last page you created (not an array). Then you try to iterate this page.
<div *ngFor="let page of pages$ | async"
This error come from the fact that you can't iterate a Page object.
You should stop using any so that this type of error occurs at compilation time, not at runtime. Also you need to store an instance of the array of page, add the item in your array after a post, and then replay the whole array.
Code
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe((res) => {
const index: number = lastSetOfData.findIndex((_page: Page) => _page._id === res._id);
lastSetOfData[index] = res;
lastSetOfData = [...lastSetOfData];
this.data.next(lastSetOfData);
});
}
Also the updateDate function should be named updatePage.
The issue is the one identified in the response from #Marco. I elaborate starting from there.
There are several ways of fixing this problem. Probably the fastest is to add an instance variable lastSetOfData to PagesService where you hold the last version of the array. Then you initiatlize lastSetOfData in the getPages method. Finally in the setPage method you update lastSetOfData appending the Page returned by the service at the end of lastSetOfData and notify it using the ReplaySubject.
So the code could look like this
export class PagesService {
public baseUrl = environment.backend;
// specify the type of data notified by the ReplaySubject
private data = new ReplaySubject<Array<Page>>();
// define lastSetOfData as an array of Pages
private lastSetOfData: Array<Page> = [];
....
public getPages() {
return this.http.get<any>(`${this.baseUrl}/page/${this.userID}`).subscribe(res => {
// res should be an array of Pages which we use to initialize lastSetOfData
lastSetOfData = res;
this.data.next(lastSetOfData)
});
}
....
public setPage(page: Page, id: string) {
const api = `${this.baseUrl}/page`;
const user_id = id;
this.http.post<any>(api, page, {
headers: { user_id }
}).subscribe(res => {
// update lastSetOfData appending resp, which should be a Page
// not the use of the spread operator ... to create a new Array
lastSetOfData = [...lastSetOfData, resp];
// now you notify lastSetOfData
this.data.next(lastSetOfData)
});
}
// probably you have to modify in a similar way also the method updateTable
public updateDate(id: string, page: Page) {
....
}
....
....
}
Consider that this may be the fastest way to fix the problem. Check if it works and then you may want to try to refactor the code to look for a more rx-idiomatic solution. But my suggestion is first to see if this fixes the problem.
Problem is that you put an object in your replaysubject although an array is expected in other places.
next(myarray)
next(myobject)
This does not magically append an object to the array.
To do so, you'd need something like this:
data.pipe(take(1)).subscribe(list => {
list.push(newvalue);
data.next(list);
});
Basically you take the last value, a the new item, and push the new list.

Values null when I make a simple post request to my .net controller from angular

This used to be a 415 error question.
Now it is a a receiving null values on the server side question.
I am having difficulty trying to get my values in the object myMessage over to the server side.
I have so far tried to add JSON.stringify to newMessage which is being console.logged in the service file.
I tried many ways to alter or make the object the way it would be recognized such as JSON.stringify() and creating a url ending with the correct parameters.
Sorry if it seems like I am dumping code below, but I have been working on this for a second day and don't understand why I can't do a simple post request with three parameters. One string, one int, and one datetime.
If anyone can see where I have gone wrong I would so appreciate it. I will be desperately waiting.
Below I am trying to hit api/SlgCorpNotes/Edit in backend from updateMessage(message: any) in the service in service.ts
slg-corp-notes.service.ts
import { Component, Injectable, Inject } from '#angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '#angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { SLGReportParams, CorpNotes } from './models/slg.model';
import { SlgOverviewComponent } from './slg-overview/slg-overview.component';
import { SlgNote } from './models/slg-notes';
#Injectable({
providedIn: 'root'
})
export class SlgCorpNotesService {
constructor(private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) { }
getWeekTempValue(endDate, department) {
var Params = '?endDate=' + endDate + '&department=' + department;
return this.http.get<any>(this.baseUrl + 'api/SlgCorpNotes/getWeekTempValue' + Params);
}
updateMessage(message: any) {
console.log("at service")
console.log(message)
var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
console.log(newMessage)
console.log(JSON.stringify(newMessage))
console.log(Params)
const headers = new HttpHeaders()
.set('Content-Type', 'application/json;charset=UTF-8')
let options = { headers: headers };
return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options).subscribe(res => {
console.log(res);
}, error => {
console.log(error);
});;
}
}
model.ts
export class CorpNotes {
constructor(
public department: number,
public note: string,
public weekEnding: Date
) { }
}
SLGCorpNotesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mocHub2.Models;
using mocHub2.Models.Enterprise;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
namespace mocHub2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SlgCorpNotesController : Controller
{
SLGContext _SLGContext;
BRDataContext _BRDataContext;
//injects new context
public SlgCorpNotesController(SLGContext context, BRDataContext context2)
{
_SLGContext = context;
_BRDataContext = context2;
}
// GET: api/SlgCorpNotes
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/SlgCorpNotes/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
// POST: api/SlgCorpNotes
[HttpPost]
public void Post([FromBody] string value)
{
}
// Get Corporate Notes
[HttpGet("[action]")]
public JsonResult getWeekTempValue(DateTime endDate, int department)
{
// Find the WeekID from the weekending from SLGHeaderTemplate table
var WeekID = (from x in _SLGContext.SlgheaderTemplate
where x.WeekEnding == endDate
select x.Id).ToList();
// Find Department name by ID
var DepartmentString = (from x in _BRDataContext.Departments
where x.Department == department
select x.Description).ToList();
// Get the Note.
var DeptNote = from x in _SLGContext.SLGCorpNotes
where x.Department == DepartmentString[0]
&& x.WeekID == WeekID[0]
select x.Notes;
// Create return object
var notes = new Notes();
// If Note exists then return Json containing note and department for display, else return empty string.
if (DeptNote.Any() && WeekID.Count() > 0 && DepartmentString.Count() > 0)
{
var ReturnDeptNote = DeptNote.First();
notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
}
else
{
var ReturnDeptNote = "";
notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
}
return Json(notes);
}
[HttpPost]
[Route("Edit")]
public void Edit([FromForm] CorpNotes item)
{
_SLGContext.Entry(item).State = EntityState.Modified;
_SLGContext.SaveChanges();
}
}
public class CorpNotes
{
public int department { get; set; }
public string note { get; set; }
public DateTime weekEnding { get; set; }
}
public class Notes
{
public int ID { get; set; }
public int WeekID { get; set; }
public string Department { get; set; }
public string Note { get; set; }
}
}
Results of console.logs in the service file.
at service
slg-corp-notes.service.ts:22 {departments: 2, weeks: SLGTime, noteBody: "asdf"}
slg-corp-notes.service.ts:25 CorpNotes {department: 2, note: "asdf", weekEnding: "2019-11-02T00:00:00"}
slg-corp-notes.service.ts:26 {"department":2,"note":"asdf","weekEnding":"2019-11-02T00:00:00"}
slg-corp-notes.service.ts:27 ?Department=2&Note=asdf&WeekEnding=2019-11-02T00:00:00
slg-corp-notes.service.ts:28 Observable {_isScalar: false, source: Observable, operator: MapOperator}
app.module.ts
This is in my app.module.ts where I specify routes
{ path: 'slg-corp-notes', component: SlgCorpNotesComponent },
{ path: 'slg-corp-notes/edit/', component: SlgCorpNotesComponent }
slg-corp-notes.component.ts
save() {
console.log("at save")
if (!this.optionsForm.valid) {
return;
}
//this.Notes.note = this.optionsForm.get['noteBody'].value;
console.log(this.Notes);
this._slgCorpNotesService.updateMessage(this.optionsForm.value)
.subscribe((data) => {
this._router.navigate(['/slg-corp-notes']); //This will navigate back to the mochhub2 index where the message will be displayed
}, error => this.errorMessage = error)
}
Please let me know if additional info is needed.
1) You need to set the Content-Type header to application/json.
2) stringify the message.
const headers = new HttpHeaders()
.set('Content-Type', 'application/json;charset=UTF-8')
let options = { headers : headers };
this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options);
At your angular side update your method like this
updateMessage(message: any) {
console.log("at service")
console.log(message)
var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
console.log(newMessage)
console.log(JSON.stringify(newMessage))
console.log(Params)
var item = {
"Departments": message["Departments"],
"Note": message["noteBody"],
"WeekEnding": message["weeks"]
}
return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', item).subscribe(res
=> {
console.log(res);
}, error => {
console.log(error);
});
}

ERR_INCOMPLETE_CHUNKED_ENCODING on angularjs - rest service returns an infinite json file using Advanced REST Client but error in postman

I have a very strange problem. In angular (app built with ionic v1) I call some REST call built in java, but something goes wrong and chrome advise me with this error:
The code interesting is this, a REST service in angular js:
bankaccountsbyuser: function(_getbauser, _error){
var currentToken = _GetToken();
if(currentToken!=null){
var Headers = {
token: currentToken.tokenUser,
};
}
_timerTokenControl(currentToken, _error);
if (setupTime == null) {
console.log("token scaduto");
//modificare
//$window.location.href="login.html";
}
if (currentToken !== null) {
$http({
method : 'GET',
headers: Headers,
url : REST_URL+'bankaccount'
}).then(function successCallback(response) {
console.log(response)
_getbauser(response)
}, function errorCallback(response) {
console.log(response.statusText);
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Accesso negato!',
template: 'Devi essere un utente registrato, non sei loggato!'
});
console.log("NON SEI LOGGATO!!!");
}
},
debug:
How you can see, the get REST service returns an error, thus, let's see this REST service built in java:
package it.jack.fdd.services;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import it.jack.fdd.dao.FactoryDao;
import it.jack.fdd.dao.impl.BankAccountDaoImpl;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.User;
import it.jack.fdd.dto.TokenUserDto;
import it.jack.fdd.dto.UserDto;
import it.jack.fdd.util.ConverterDTO;
#Path("/bankaccount")
public class BankAccountServices {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<BankAccount> getBankAccountOfUser() {
BankAccountDao baDao = new BankAccountDaoImpl();
List<BankAccount> balist = baDao.getBAByUserId(1);
return balist;
}
I tryed to pass the number "1" in the method, just to simplify. The method is implemented below:
package it.jack.fdd.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.Staff;
import it.jack.fdd.domain.User;
import it.jack.fdd.util.HibernateUtilLezione;
public class BankAccountDaoImpl extends BaseDaoImpl<BankAccount> implements BankAccountDao{
public List<BankAccount> getBAByUserId(int id) {
try{
Session session = HibernateUtilLezione.openSession();
Transaction tx = session.beginTransaction();
#SuppressWarnings("unchecked")
List<BankAccount> accounts = session.createQuery("from BankAccount b "
+ "where b.user= "+id).list();
tx.commit();
session.close();
return accounts;
}
catch(HibernateException e){
e.printStackTrace();
return null;
}
}
}
As you can see, the method ask for an id, and I put id 1 just to check, because in the database there is a field with that id. Trying in java, it returns me a list
[it.jack.fdd.domain.BankAccount#4f8d86e4]
And I checked also that the list has dimension 1 (thus, only one record, like in the database, only 1 record with that iduser)
Thus, trying to open this REST call using postman, the result is this:
The strange thing is that postman show me the same result to another REST call, that it worked before. But for this last REST call is not a problem, because strangely it works on my application, it doesn't work only in postman.
Thus, trying with Advanced REST Client I have a strange different result:
A strange, very big list that repeat every time the same field!! It is like a loop!
What happens? How I can solve?
Solved. The problem was in java's domain classes: when a domain class has a one-to-many relationship it's mandatory to put the tag #JsonIgnore to avoid these recurrent records in json file
Entity class:
package it.jack.fdd.domain;
// Generated 30-nov-2016 0.17.09 by Hibernate Tools 4.3.1.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* BankAccount generated by hbm2java
*/
#Entity
#Table(name = "bank_account", catalog = "fdd_dbproducts")
public class BankAccount implements java.io.Serializable {
private Integer idbankAccount;
private User user;
private String iban;
private String pin;
private String society;
private Date expiration;
public BankAccount() {
}
public BankAccount(User user, String iban, String pin, String society) {
this.user = user;
this.iban = iban;
this.pin = pin;
this.society = society;
}
public BankAccount(User user, String iban, String pin, String society, Date expiration) {
this.user = user;
this.iban = iban;
this.pin = pin;
this.society = society;
this.expiration = expiration;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idbank_account", unique = true, nullable = false)
public Integer getIdbankAccount() {
return this.idbankAccount;
}
public void setIdbankAccount(Integer idbankAccount) {
this.idbankAccount = idbankAccount;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "fkuser_baccount", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "iban", nullable = false, length = 45)
public String getIban() {
return this.iban;
}
public void setIban(String iban) {
this.iban = iban;
}
#Column(name = "pin", nullable = false, length = 45)
public String getPin() {
return this.pin;
}
public void setPin(String pin) {
this.pin = pin;
}
#Column(name = "society", nullable = false, length = 45)
public String getSociety() {
return this.society;
}
public void setSociety(String society) {
this.society = society;
}
#Temporal(TemporalType.DATE)
#Column(name = "expiration", length = 10)
public Date getExpiration() {
return this.expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
}

displaying data from restful service in react UI through nodejs

I've developed a restful webservice which displays a simple data using below code.
package com.mike;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MessageController {
#RequestMapping(value="/message",method=RequestMethod.GET)
public Message print(){
return new Message(1,"Hello Mike!!");
}
}
and the bean is as follows....
package com.mike;
public class Message {
private int id;
private String message;
public Message(int id, String message){
this.id=id;
this.message=message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMesssage(String message) {
this.message = message;
}
}
now I want to display this data in an Nodejs application, so I wrote a file named app.js and wrote the following code to display data in the console.and it worked fine. but i don't know how to integrate this nodejs application with reactjs UI so that i can display in on a web page. so please kindly help me, I am new to both node and react.the code for app.js is below...
var http=require('http');
var extServerOptions={
host:'localhost',
port:'8080',
path:'/message',
method:'GET'
};
var mes=[];
var x;
var text="";
function get(){
http.request(extServerOptions,function (res){
res.setEncoding('utf8');
res.on('data',function(data){
mes=JSON.parse(data);
console.log(mes);
for(x in mes){
text+=mes[x]+" ";
};
console.log(text);
});
}).end();
};
get();
please kindly say me the stepps i need to do in order to display data in a react page.

Some of data comes null in java spring and react js

I want to save all data by using react.js and Java Spring. I sent data with REST, but one of data class comes null to collections in MongoDB. I controlled whether or not all data types are equal. I cannot see and solve my errors. I share both Spring data type definitions and react.js definitions.
BildirimGrubu comes null
Java Spring:
package tr.com.innova.watcher;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.util.List;
/**
* Created by SBK on 03.09.2016.
*/
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class BildirimGrubu {
String emailMetni;
String smsMetni;
List<Alici> alici;
enum EmailEkTipi{
HICBIRI, EXCEL, PDF
};
EmailEkTipi ekTip;
enum BildirimYontemi{
EMAIL, SMS, HEPSI, HICBIRI
};
BildirimYontemi bildirimYont;
int mesajSayisi;
int mesajKarakter;
}
React.js:
import * as React from "react";
export enum EmailEkTipi{
HICBIRI, EXCEL, PDF
}
export enum BildirimYontemi {
EMAIL, SMS, HEPSI, HICBIRI
}
export enum TetikleyiciTipi{
CRON, SIMPLE
}
export class Alici {
label:string;
value:string;
constructor(name:string,
val:string) {
this.label = name;
this.value = val;
}
}
export class BildirimGrubu {
emailMetni:string;
smsMetni:string;
alici:Array<Alici>;
ekTip:EmailEkTipi;
bildirimYont:BildirimYontemi;
mesajSayisi:number;
mesajKarakter:number;
constructor(emailMetni:string, smsMetni:string, alici:Array<Alici>, ekTip:EmailEkTipi, bildirimYont:BildirimYontemi, mesajSayisi:number,mesajKarakter:number) {
this.emailMetni = emailMetni;
this.smsMetni = smsMetni;
this.alici = alici;
this.ekTip = ekTip;
this.bildirimYont = bildirimYont;
this.mesajSayisi = mesajSayisi;
this.mesajKarakter = mesajKarakter;
}
}
export class Tetikleyici {
tetikleyiciAdi:string;
aciklama:string;
tetikleyiciIcerik:TetikleyiciTipi;
durum:boolean;
bildirimGrubu:BildirimGrubu;
tip:TetikleyiciTipi;
bildirimEkle:boolean;
constructor(tetikleyiciAdi:string, aciklama:string, tetikleyiciIcerik:TetikleyiciTipi, durum:boolean, bildirimGrubu:BildirimGrubu, tip:TetikleyiciTipi, bildirimEkle:boolean) {
this.tetikleyiciAdi = tetikleyiciAdi;
this.aciklama = aciklama;
this.tetikleyiciIcerik = tetikleyiciIcerik;
this.durum = durum;
this.bildirimGrubu = bildirimGrubu;
this.tip = tip;
this.bildirimEkle = bildirimEkle;
}
}
export class Sorgu {
_id:string;
userName:string;
anaSorgu:string;
aciklama:string;
altSorguList:Array<string>;
tetikleyici:Tetikleyici;
sName:string;
constructor(id:string, username:string, anaSorgu:string, aciklama:string, altSorguList:Array<string>, tetikleyici:Tetikleyici, sName:string) {
this._id = id;
this.userName = username;
this.anaSorgu = anaSorgu;
this.aciklama = aciklama;
this.altSorguList = altSorguList;
this.tetikleyici = tetikleyici;
this.sName=sName;
}
}
Data to send DB with REST:
[new Sorgu("1","Hi","select","select sorgusu",["hi","hoy"],new Tetikleyici("tetikle", "hello", TetikleyiciTipi.CRON, true, new BildirimGrubu("a", "a", [["ali","bak"]], EmailEkTipi.EXCEL, BildirimYontemi.HEPSI, 1, 1), TetikleyiciTipi.CRON, true),"sorgu_8")]
I hope to transferred you my problems. Thank you for helps.
While again created classes, I realized that I forgot to add public. Therefore, java cannot access the objects of the class. Don't forget public. :)
Even so, thank you!

Categories