NativeScript with angular gives a run time error - nativescript-angular

I just tried a connect with my Native-script app.In app.component.ts file i have create my database and two methods.
export class AppComponent {
private database: any;
private people: Array<any>;
public constructor() {
console.log(" database service constructors");
(new Sqlite("my.db")).then(db => {
db.execSQL("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT, lastName Text)").then(db => {
this.database = db;
}, error => {
console.log("CREATE TABLE ERROR", error);
})
}, error => {
console.log("CREATE DB ERROR", error);
})}
public insert() {
console.log("Acess Insert Ok");
this.database.execSql("INSERT INTO people (firstName, lastName) VALUES (?,?)", ["Randika", "Perera"]).then(id => {
console.log("Insert Ok");
this.fetch();
}, error => {
console.log("INSERT ERROR: ", error);
})}
public fetch() {
this.database.all("SELECT * FROM people").then(rows => {
this.people = [];
for (let row in rows) {
this.people.push({
"id": rows[row][0],
"firstName": rows[row][1],
"lastName": rows[row][2]
})
}
}, error => {
console.log("SELECTOR ERROR:", error);
});}}
In app.component.hlml file:
<ActionBar title="My App">
<ActionItem text="Add" (tap)="insert()"></ActionItem>
But after clicking add button and it gives a error like
W/System.err(10737): at com.tns.Runtime.callJSMethodNative(Native Method)
W/System.err(10737): at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1197)
W/System.err(10737): at com.tns.Runtime.callJSMethodImpl(Runtime.java:1061)
W/System.err(10737): at com.tns.Runtime.callJSMethod(Runtime.java:1047)
W/System.err(10737): at com.tns.Runtime.callJSMethod(Runtime.java:1028)
W/System.err(10737): at com.tns.Runtime.callJSMethod(Runtime.java:1018)
Can anyone help with this?

When i'm searching more on it in emulator there is a error like " execSql is not a function". so i change it to execSQL like i used top of the and now its working fine.

Related

How can i get many details as possible about error using React Error boundry get error details?

Im tring to catch more details when error accuring.
when the error is accuring im using node api server to catch the error and save in log file.
i simulated a Network Error and tring to get many details as possible.
when i console.log the error in frontend im getting this:
withFormHandler.js:28 Uncaught Error: Error: Network Error
at Object.componentDidUpdate (withFormHandler.js:28)
...
but i cant send this information using my api.
all im getting in the server side is an empty object.
so how can i catch and send many details as possible about the error and write it to the log file?
this is my ErrorBoundry component:
class ErrorBoundary extends React.Component {
state = {
hasError: false,
error: { message: "", stack: "" },
info: { componentStack: "" },
};
static getDerivedStateFromError = (error) => {
return { hasError: true };
};
componentDidCatch = (error, info) => {
this.setState({ error, info });
axios
.get(`http://localhost:5001/api/logs/error`, {
params: {
error: error.message,
details: info,
// details:error ---> this is also not give me information i need
},
})
.catch(() => {});
};
render() {
const { hasError, error, info } = this.state;
const { children } = this.props;
return hasError ? <ErrorComponent message={error.message} /> : children;
}
}
this is the server side handle:
router.get("/error", (req, res) => {
const errorMessage = req.query.error;
const details = req.query.details; -----> return an empty object :(
const logFile = "./logs/debug.log";
if (errorMessage) {
let error = errorMessage + "\r\n" + details;
fs.appendFile(logFile, error, function (err) {
// callback or something
});
}
});

Passing function to Knex select method breaks querying

The code:
const knex = require("../../db/knex");
module.exports = (request, response) => {
knex
.select((builder) => {
const select = request.query.select;
if (select) {
if (select.constructor === String) {
builder.select(select);
} else if (select.constructor === Array) {
builder.select(...select);
}
} else {
/* Anything that goes here or inside this function, breaks it. */
}
})
.from("tags")
.where((builder) => {
const filter = request.query.filter;
if (filter) {
if (filter.constructor === Object) {
builder.where(filter);
} else if (filter.constructor === Array) {
builder.where(...filter);
}
} else {
builder.clear("where");
}
})
.then((result) => response.json(result))
.catch((error) => response.json({ ...error, message: error.stack }));
};
The full error:
{
"length": 180,
"name": "error",
"severity": "ERROR",
"code": "42601",
"position": "16",
"file": "d:\\pginstaller_13.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_target.c",
"line": "1296",
"routine": "ExpandAllTables",
"message": "error: select (select *) from \"tags\" - SELECT * with no tables specified is not valid\n at Parser.parseErrorMessage (C:\\Users\\Lucas\\Desktop\\Repositories\\projeto-integrador-dh-g1\\node_modules\\pg-protocol\\dist\\parser.js:278:15)\n at Parser.handlePacket (C:\\Users\\Lucas\\Desktop\\Repositories\\projeto-integrador-dh-g1\\node_modules\\pg-protocol\\dist\\parser.js:126:29)\n at Parser.parse (C:\\Users\\Lucas\\Desktop\\Repositories\\projeto-integrador-dh-g1\\node_modules\\pg-protocol\\dist\\parser.js:39:38)\n at Socket.<anonymous> (C:\\Users\\Lucas\\Desktop\\Repositories\\projeto-integrador-dh-g1\\node_modules\\pg-protocol\\dist\\index.js:10:42)\n at Socket.emit (events.js:315:20)\n at addChunk (internal/streams/readable.js:309:12)\n at readableAddChunk (internal/streams/readable.js:284:9)\n at Socket.Readable.push (internal/streams/readable.js:223:10)\n at TCP.onStreamRead (internal/stream_base_commons.js:188:23)"
}
I'm using Express to manage the Node server and Knex to manage the database. In this route, if I remove the function from select, everything works. Tried everything, I can't understand why isn't working. Can anyone help me understand why is it breaking?
The select() method in Knex takes in column names to select from your table. I don't think you can properly pass in a function like you're trying to do. You can do that in the .where() like you have. But I'd start by removing all of the if/else logic from inside of select().
If you need to transform the data you're receiving, do that prior to building a query. Perhaps there might be other query building methods that would help you get the result that you're looking for.
As stated in the comment, what is being done is considered by Knex a sub query. I've found out that the proper way to handle these conditions are by using modify.
I got to something like this now:
const knex = require("../../db/knex");
module.exports = (request, response, next) => {
knex
.from("tags")
.modify((builder) => {
const filter = request.query.filter;
const select = request.query.select;
const order = request.query.order;
const id = request.params.id;
if (select) {
if (select.constructor === String || select.constructor === Object) {
builder.select(select);
} else if (select.constructor === Array) {
builder.select(...select);
}
}
if (id) {
builder.where({ id: id }).first();
} else if (filter) {
if (filter.constructor === Object) {
builder.where(filter);
} else if (filter.constructor === Array) {
builder.where(...filter);
}
}
if (!id) {
if (order) {
if (order.constructor === String) {
builder.orderBy(order);
} else if (order.constructor === Array) {
builder.orderBy(...order);
}
}
}
})
.then((result) => response.json(result))
.catch((error) => next(error));
};

Error getting salesOrder in Netsuite while getting a record

Unable to get single NetSuite salesOrder, Generating below error
Getting Sales Order record
Error
[
{
'$attributes': { type: 'ERROR' },
code: 'INVALID_TRANS_TYP',
message: 'Transaction type specified is incorrect.'
}
]
{
"readResponse": {
"status": {
"$attributes": {
"isSuccess": "false"
},
"statusDetail": [
{
"$attributes": {
"type": "ERROR"
},
"code": "INVALID_TRANS_TYP",
"message": "Transaction type specified is incorrect."
}
]
}
}
}
Last Request:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="urn:platform_2014_2.webservices.netsuite.com" xmlns:platformMsgs="urn:messages_2014_2.platform.webservices.netsuite.com" xmlns:platformFaults="urn:faults_2014_2.platform.webservices.netsuite.com" xmlns:platformCore="urn:core_2014_2.platform.webservices.netsuite.com" xmlns:platformCommon="urn:common_2014_2.platform.webservices.netsuite.com" xmlns:listRel="urn:relationships_2014_2sales.transactions.webservices.netsuite.com" xmlns:tranSales="urn:sales_2014_2.transactions.webservices.netsuite.com" xmlns:actSched="urn:scheduling_2014_2.activities.webservices.netsuite.com" xmlns:setupCustom="urn:customization_2014_2.setup.webservices.netsuite.com" xmlns:listAcct="urn:accounting_2014_2.lists.webservices.netsuite.com" xmlns:tranBank="urn:bank_2014_2.transactions.webservices.netsuite.com" xmlns:tranCust="urn:customers_2014_2.transactions.webservices.netsuite.com" xmlns:tranInvt="urn:inventory_2014_2.transactions.webservices.netsuite.com" xmlns:listSupport="urn:support_2014_2.lists.webservices.netsuite.com" xmlns:tranGeneral="urn:general_2014_2.transactions.webservices.netsuite.com" xmlns:listMkt="urn:marketing_2014_2.lists.webservices.netsuite.com" xmlns:listWebsite="urn:website_2014_2.lists.webservices.netsuite.com" xmlns:fileCabinet="urn:filecabinet_2014_2.documents.webservices.netsuite.com" xmlns:listEmp="urn:employees_2014_2.lists.webservices.netsuite.com"><soap:Header><platformMsgs:passport><platformCore:email>darshan.sanandiya#techholding.co</platformCore:email><platformCore:password>techh#123#</platformCore:password><platformCore:account>5022995_SB1</platformCore:account><platformCore:role internalId="3"></platformCore:role></platformMsgs:passport></soap:Header><soap:Body><platformMsgs:get xmlns:platformMsgs="urn:messages_2014_2.platform.webservices.netsuite.com" xmlns="urn:messages_2014_2.platform.webservices.netsuite.com"><platformMsgs:baseRef type="salesOrder" xsi:type="platformCore:RecordRef" internalId="106095" externalId="106095"></platformMsgs:baseRef></platformMsgs:get></soap:Body></soap:Envelope>
All I want to fetch single order with internalId, But in return, it throws INVALID transction type error;
I am using npm soap; and netsuite sdk with nodejs
'use strict';
var denodeify = require('denodeify');
var NetSuite = require('../');
var credentials = require('../example/credentials.json');
var config = new NetSuite.Configuration(credentials);
var service = new NetSuite.Service(config);
console.log('Creating NetSuite connection');
console.log(service,"Service<<<")
service
.init()
.then(function( /*client*/ ) {
console.log('WSDL processed. Service description:');
console.log(service.config.client.describe());
var recordRef = new NetSuite.Records.RecordRef();
recordRef.internalId = "106095";
recordRef.type = 'salesOrder';
console.log('Getting Sales Order record');
return service.get(recordRef);
})
.then(function(result, raw, soapHeader) {
if (result.readResponse.status.$attributes.isSuccess !== 'true') {
console.error('Error');
console.error(result.readResponse.status.statusDetail);
}
console.log(JSON.stringify(result, null, 2));
console.log('Last Request:');
console.log(service.config.client.lastRequest);
})
.catch(function(err) {
console.error(err);
console.error('Last Request:');
console.error(service.config.client.lastRequest);
});
Above is the code I am executing to get salesOrder;
Believe the Record Type you want is SalesOrder, not salesOrder.
Reference: https://system.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2019_2/schema/record/salesorder.html

can't use a member function inside fetch call

I get a response from a fetch call and i'm trying to check if the respond correspond to a kind of error my server is likely to respond me if the username or the email sent already exist in my database. If this is the case, i try to use a member function of my class to show a error message to the user. But when i try to use my member function i get the error:
Unhandled Rejection (TypeError): Cannot read property 'showValidationErr' of undefined.
I think that i can't use a member function in that case, how can i call my member function when i catch a error from my server ?
class RegisterBox extends React.Component {
constructor(props) {
super(props);
this.state = {username: "",
email: "",
password: "",
confirmPassword: "",
errors: [],
pwdState: null};
}
showValidationErr(elm, msg) {
this.setState((prevState) => ( {errors: [...prevState.errors, {elm, msg} ] } ) );
}
submitRegister(e) {
fetch("http://localhost:8080/register?user=" + this.state.username + "&psw=" + this.state.password + "&email=" + this.state.email)
.then(function (respond) {
return respond.text()
.then(function(text) {
if (text === "RegisterError : username") {
this.showValidationErr("username", "username allready taken.");
}
if (text === "RegisterError : email") {
this.showValidationErr("email", "email allready used.");
}
})
});
}
}
I found how to correct it. i needed to add the line "var that = this;" at the beginning of my function and use "that.showValidationErr();" instead.
In this context, this refers to the anonymous callback function() that you're passing to the then(). Try using the arrow function syntax instead which keeps the this as the surrounding context.
.then((respond) => {
return respond.text()
.then((text) => {
if (text === "RegisterError : username") {
this.showValidationErr("username", "username allready taken.");
}
if (text === "RegisterError : email") {
this.showValidationErr("email", "email allready used.");
}
})

Angular and Node.js: Get Call parse Data into object

I am new at Angular and I am trying to create a dashboard for plants. So I want to display data from a MySQL database to my Angular app. To pass the plantdata to Angular I use node.js. I have already managed to present a list of my plants. Now I want to display the details for each plant. But the data isn't displayed, because the object plant is undefined. If I try to call directly my node.js server via browser, it works and displays the data as JSON.
I found out, that the data is transferred to my app as JSON correctly and I can display it as a JSON string on my website. I thinks there is a problem to parse the received data from the server into the plant object, because I can't get a vaule by using the dot notation like {{plants.id}} at the HTML. When I try this I got an error like this:
ERROR TypeError: Cannot read property 'id' of undefined
at Object.eval [as updateRenderer] (PlantDetailComponent.html:11)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735)
at checkAndUpdateView (core.js:13849)
at callViewAction (core.js:14195)
at execComponentViewsAction (core.js:14127)
at checkAndUpdateView (core.js:13850)
at callViewAction (core.js:14195)
at execEmbeddedViewsAction (core.js:14153)
at checkAndUpdateView (core.js:13845)
at callViewAction (core.js:14195)
ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}
The method getPlant is similar to the method getPlants which works and parses the data correctly.
How can I parse the data into the plant object correctly?
Here is my Angular code:
plant.service:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { catchError, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { Plant } from './plant';
#Injectable()
export class PlantService {
private plantsUrl = 'api/plants';
constructor(private http: HttpClient) { }
getPlants(): Observable<Plant[]> {
return this.http.get<Plant[]>(this.plantsUrl)
.pipe(
catchError(this.handleError('getPlants', []))
);
}
getPlant(id: number): Observable<Plant> {
const url = `${this.plantsUrl}/${id}`;
return this.http.get<Plant>(url).pipe(
catchError(this.handleError<Plant>(`getPlant id=${id}`))
);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
};
}
}
plant-detail.component:
import { Component, OnInit, Input } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Location } from '#angular/common';
import { Plant } from '../plant';
import { PlantService } from '../plant.service';
#Component({
selector: 'app-plant-detail',
templateUrl: './plant-detail.component.html',
styleUrls: ['./plant-detail.component.css']
})
export class PlantDetailComponent implements OnInit {
plant: Plant;
constructor(private route: ActivatedRoute,
private plantService: PlantService,
private location: Location
) {}
ngOnInit(): void {
this.getPlant();
}
getPlant(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.plantService.getPlant(id)
.subscribe(plant => this.plant = plant);
}
goBack(): void {
this.location.back();
}
}
The component and the service are registered in the app.module. I also registered the HttClientModule.
my Node Server:
var express = require("express");
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'plant_care',
});
var app = express();
app.get("/api/plants", function(req, res) {
connection.query('SELECT * FROM plant', function(err, rows, fields) {
if (!err)
res.send(rows);
else
console.log('Error while performing Query.');
});
});
app.get("/api/plants/:id", function(req, res) {
const requestedID = req.params.id;
connection.query('SELECT * FROM plant WHERE ID = ' + requestedID, function(err, rows, fields) {
if (!err)
res.send(rows);
else
console.log('Error while performing Query.');
});
});
app.listen(3000, function() {
console.log("Running...");
});
I solved it.
My server has sent the data from the MySQL database as an array.
But my function in plant.service did not expect an array.
So there were two ways for me to solve the problem. Either I change the service function that it expects an array, or I change the server that it no longer sends a single record in form of an array.
I decided to change the server function:
app.get("/api/plants/:id", function(req, res) {
const requestedID = req.params.id;
connection.query('SELECT * FROM plant WHERE ID = ' + requestedID, function(err, rows, fields) {
if (!err)
res.send(rows[0]);
else
console.log('Error while performing Query:\n' + err);
});
});

Resources