Access the common method from other component - html

Here I am using some method for frequently used methods in common method ts file. If I am going to access these method I got null values Please help me out.
CommonMethod.ts:
GetCategoryList(){
let Mylist = [];
this.auth.Get("Master/Category").then((user) => {
Mylist= user.json();
});
return Mylist;
}
My Another component:
I am trying to access common method ts file here. by below way.
import {CommonMethod} from './CommonMethod';
...
...
construtor(private com:CommonMethod){}
ngOninit(){
console.log(this.com.GetCategoryList());
}

this.auth.Get is going to be async in nature due to which the return MyList line will get called even before the callback to the then method is called and the data is arrived and set in MyList.
You can use the async await syntax to fix it:
async GetCategoryList() {
let Mylist = [];
const user = await this.auth.Get("Master/Category");
Mylist = user.json();
return Mylist;
}
You can then use it like this in your Component:
import {CommonMethod} from './CommonMethod';
...
...
construtor(private com: CommonMethod) {}
async ngOninit() {
const myList = await this.com.GetCategoryList();
console.log(myList);
}
PS: Make sure that CommonMethod is a service and is added to the providers array of your #NgModule

Should update your common method:
GetCategoryList(): Promise<any>{
let Mylist = [];
return this.auth.Get("Master/Category").then((user) => {
Mylist= user.json();
Promise.resolve(Mylist);
});
}
And
ngOninit(){
this.com.GetCategoryList().then(results=>{
console.log(results);
});
}

Related

TypeScript correctly type a queryresult MySQL

I am using the mysql2/promise npm package for connecting and doing queries to a MySQL database. I got confused trying to set the correct typing for my query result, because I don't know in advance what type the result will be.
I have created a database class that has an async query method.
// Database.ts
import mysql, { Pool } from "mysql2/promise"; // import mysql2/promise
export class Database implements IDatabase {
logger: ILogger;
pool: Pool;
constructor(logger: ILogger) {
this.logger = logger;
// pool connection is set up here
}
async query(sql: string, options?: unknown): Promise<unknown> { // type?
const [rows] = await this.pool.query(sql, options);
return rows;
}
}
In my server code, I would like to be able do something like this:
// server.ts
import { Database } from "./core/Database";
const db = new Database(logger);
app.get("/", async (req, res) => {
const sql = `
select *
from users;
`;
const users: IUser[] = await db.query(sql); // get people
// do some logic x
// send response
res.json({
result: x
});
});
Using unknown doesn't work because I can't assign it to my type, using any does, but feels wrong. Is there a clean way to do this?
Type the function as:
async query<T = unknown>(sql: string, options?: unknown): Promise<T[]> {
Then use the function this way:
const users = await db.query<IUser>(sql);
With help of #Evert and this answer, I found a solution
I created following types:
export type DbDefaults = RowDataPacket[] | RowDataPacket[][] | OkPacket[] | OkPacket;
export type DbQueryResult<T> = T & DbDefaults;
Rewrote my method like this:
async query<T>(sql: string, options?: unknown): Promise<DbQueryResult<T[]>> {
const [result] = await this.pool.query<DbQueryResult<T[]>>(sql, options);
return result;
}
I can use it like this now:
const sql = `
select *
from users;
`;
const people = await db.query<IUser>(sql);
Just casting as T is also possible.
public async query<T>(sql: QueryString, parameters?: unknown[]): Promise<T[]> {
const [rows] = await this.pool.query(sql, parameters);
return rows as T[];
}

how to access a function in a promise

my code in react application
I have I class:
class SampleModuleController{
getSampleModuleSheet()
{
console.log("getSampleModuleSheet");
return tableSheet;
}
retrivePageData(pageNumber,pageLength){
console.log("retrivePageData calledd");
let pageData= asyncAwaitService.findTablePageTestData(pageNumber,pageLength);
return pageData;
}
}
export let sampleModuleController = new SampleModuleController();
SampleModuleController class lazy loaded and its getSampleModuleSheet method can use successfully.
in jsx:
<DataTable getPageData={import('../controllers/sampleModuleContrller').then(({sampleModuleController}) => {return sampleModuleController.retrivePageData;})} />
in js file:
async newPageManager(){
console.debug("this.props.getPageData------",this.props.getPageData);
let pageData = await props.getPageData(1,34);
}
out put
so how can I call the fuction inside the promise
in your jsx, it's apparent that the promise returns a method delegate.
So, this.props.getPageData when resolved with await will result in a method delegate that is itself to be invoked on.
we'll modify your snippet as followed;
async newPageManager(){
console.debug("this.props.getPageData------",this.props.getPageData);
let getPageData = await props.getPageData;
let pageData = getPageData(1,34);
}
additionally, since props.getPageData is returning a promise, it is thenable.
so, you could pass the result of that promise into a then function scope -- something like the following
async newPageManager(){
console.debug("this.props.getPageData------",this.props.getPageData);
let getFirstPagePromise = props.getPageData.then((fn) => fn.bind(this, 1, 32));
let getFirstPage = await getFirstPagePromise;
let pageData = getFirstPage();
}

Retrieve documentId from future

I have not been able to find an answer to my problem so I will ask here.
I created a document that contains one piece of data. Once that document is created I need to retrieve the id of that document so I can use that string to add to another document that will be created next. The code is below where I call the Future function "saveNewAgency" as well as the code for the Future function.
if (globals.newAgency == true) {
firestoreService.saveNewAgency(newAgency);
agentProvider.saveAgent();
globals.newAgency = false;
} else {
firestoreService.saveAgency(newAgency);
}
Future<String> saveNewAgency(Agency agency) async {
DocumentReference docRef = await _db
.collection('agency')
.add(agency.toMap())
.then((value) => value.id);
//globals.agencyId = docRef.id;
}
As you can see I tried to set a global variable inorder to get the documentId but that code never gets executed so I commented it out.
This is a small thing but it is just another step I have reached in my journey of learning flutter and firebase.
Thanks
String Id = _db .collection('agency').doc().id;
Future<String> saveNewAgency(Agency agency) async {
await _db
.collection('agency')
.doc(id)
.set(agency.toMap())
.then((value) => {
print(id);
});
}
Try this.
Future<String> saveNewAgency(Agency agency) async {
await _db
.collection('agency')
.add(agency.toMap())
.then((value) => {
globals.agencyId = value.id
});
}

How to check the existence of file before reading it in Angular?

I have a function that gets the data from a saved file into the myJson variable. How can I check that the file exists without it affecting the below methods? Also, the file is in another folder that the one of the src of the project. It is in the backend dedicated folder. How can I access it from Angular and also to check if the file exists?
import myJson from 'src/assets/myFile.json' ;
readFile() {
this.savedData=myJson;
console.log("this is data from file "+this.savedData);
return myJson;
}
constructor (){
this.savedData= this.readFile();
}
Giving more context to my comments, I would do the async function as follow:
public async readFile() {
return await new Promise((resolve,reject) => {
this.http.get("your_path_to_file").toPromise().then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
}
Then the funcion that calls the readFile :
public getFile() {
this.saveData = this.readFile();
// more code here if needed
}
Then instead of calling it in the constructor I'd use the OnInit life cycle:
public ngOnInit(): void {
this.getFile();
}
More datails on why it's a bad practise to return a promise in the constructor here: Is it bad practice to have a constructor function return a Promise?

Use data accross all components

Created a component where I call all my api's. How do I use that data across all my other components
export let resultData = axios
.get(`https://swapi.dev/api/people/1`) //used a dummy api to test
.then(({ data }) => data);
export default class CacheService {
static myInstance = null;
result = resultData;
static getInstance() {
if (CacheService.myInstance == null) {
CacheService.myInstance = new CacheService();
}
return this.myInstance;
}
findAll() {
console.log(this.result);
return this.result;
}
}
You have created a promise and assigned to resultData variable but its not actually resolved.
Either you can use await or use then to get the data.
let testData = await newData.findAll();
or
newData.findAll().then((data)=>{
testData = data;
});
You need to await for the axios to resolve.
async findAll() {
const actualResult = await this.result;
console.log(actualResult);
return actualResult;
}