Get Data from NodeJs to Angular - node.js

I want to get some data from nodejs to angular and list it on a web page.
I tried to do it but i get no answer (the web page is blank, no errors)
this is the post.model:
export interface Post {
id: string;
token: string;
lat: String;
lng: String;
}
The JSON I'm working on (from database):
{
"location": [
{
"_id": "5f3429f9fe89ef3658c5ec17",
"lat": "44.4363255",
"lng": "25.9912393",
"token": "edb153fb9d8d5628",
"__v": 0
},
{
"_id": "5f342fbadae3a42884852505",
"lat": "44.4363228",
"lng": "25.9912314",
"token": "c30af1934c22f4eb",
"__v": 0
}
]
}
post-list.component:
export class PostListComponent implements OnInit, OnDestroy {
posts: Post[] = [];
private postsSub: Subscription;
constructor(public postsService: PostsService) {
//dependency-injection
}
ngOnInit() {
this.postsService.getPosts();
this.postsSub = this.postsService
.getPostUpdateListener()
.subscribe((posts: Post[]) => {
this.posts = posts;
});
}
onShow() {
console.log('TODO');
}
ngOnDestroy() {
this.postsSub.unsubscribe();
}
post-list.component.html:
<mat-accordion multi="true" *ngIf="posts.length > 0">
<mat-expansion-panel *ngFor="let post of posts">
<mat-expansion-panel-header>
{{ post.token }}
</mat-expansion-panel-header>
<p>{{ post.lat }}</p>
<p>{{ post.lng }}</p>
<mat-action-row>
<button mat-raised-button color="accent" (click)="onShow(post.id)">
SHOW
</button>
</mat-action-row>
</mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf="posts.length <= 0">No posts added yet</p>
and also the post.service:
export class PostsService {
private posts: Post[] = [];
private postsUpdated = new Subject<Post[]>();
constructor(private http: HttpClient) {}
getPosts() {
this.http
.get<{ posts: any[] }>('127.0.0.1:8000/location')
.pipe(
map((postData) => {
return postData.posts.map((post) => {
return {
id: post._id,
token: post.token,
lat: post.lat,
lng: post.lng,
};
});
})
)
.subscribe((transformedPosts) => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]);
});
}
getPostUpdateListener() {
return this.postsUpdated.asObservable();
}
Basically I'm retrieving some data from a android app and save it on a mongodb database using nodejs.
The next step of my project is to list the data from the database on a web page.
I tried to get the data via getPosts() method (see post.service), then list it. As I told you, nothing shows on the web page.
the app.component.html is simple, I just called an to show a map (I will show some coords on a map later) and the , which should show the data from the database.
If i delete the <app-post-list></app-post-list>, the webpage displays a google map, so the rest of the code is working, but when i add <app-post-list></app-post-list>, it doesn't show anything anymore.
Any ideas, please?
---Edit
I resolved the "nothing appearing issue".
Now, the data can't be displayed: No posts added yet
this is the developer console log:

From your last comment, i think you just forgot to import HttpClientModule in your AppModule.
Make sure to add schema "http://" to your target url, like this:
.get<{ posts: any[] }>('http://127.0.0.1:8000/location')
If you don't do so, Angular will just interpret it as http://localhost:4200/127.0.0.1/location

Related

How to find and print array of objects in mongoDB document

I have this document in mongoDB:
{
"_id": {
"$oid": "628f739398580cae9c21b44f"
},
"events": [
{
"eventName": "Dans",
"eventText": "Danse",
"eventDate": "010101"
},
{
"eventName": "Spill",
"eventText": "Spille",
"eventDate": "020202"
}
],
"school": "Høyskolen Kristiania"
}
I am trying to get each event (name, text and date) in their own div, but can't seem to access each "block" by their own. They are supposed to be printed as one, and only where school matches, and my intention was to make different documents for each school and filter by query from there. That though, is not an issue. I am able to get all of them as one array of objects or like
{
[dev:server] _id: new ObjectId("628f739398580cae9c21b44f"),
[dev:server] events: [ [Object], [Object] ],
[dev:server] school: 'Høyskolen Kristiania'
[dev:server] }
My API currently looks like this:
Name of course is going to be sent in by userinfo, hardcoded for testing purposes.
router.get("/", async (req, res) => {
const name = "Høyskolen Kristiania";
const schools = await mongoDatabase
.collection("tempschool")
.find()
.toArray();
console.log(schools);
res.json(schools);
});
And my client:
function EventCard({ event }) {
const { eventName, eventDate, eventText } = event;
return (
<div>
<h1>{eventName}</h1>
<h3>{eventDate}</h3>
<div>{eventText}</div>
</div>
);
}
export function SchoolPage() {
const {loading, error, data} = useLoader(
async () => await fetchJSON("/api/schools")
);
const school = data;
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return (
<div>Error</div>
);
}
return (
<div>
{school.map((event) => (
<div key={event.name}>
<EventCard event={event}/>
</div>
))}
</div>
);
}
I don't know if you've created tempschool as a MongooseSchema or not. You should though, you will then query it as
const school = await TempSchool.findOne({school: "Høyskolen Kristiania"});
school.events will then give you an array of objects. You will use it on front-end as
return(
<div>
school.events.map((event) => (
<div>
<h1>{event.eventName}</h1>
<h3>{event.eventDate}</h3>
<div>{event.eventText}</div>
</div>
)
)
</div>
);

How access Fauna's "after" cursors in Next.js API routes

I am building an application using Next.Js and Fauna where when a user visits the /accounts route, it fetches Next.js API route /api/fauna/accounts which makes a query to Fauna to get all the accounts the user owns then returns that response to the page and renders the data in a table.
Fetch inside /accounts looks like so:
function Accounts() {
const [data, setData] = useState(null)
useEffect(() => {
fetch('api/accounts')
.then((res) => res.json())
.then((data) => {
setData(data)
})
}, [])
return (
<Table>
{...data}
</Table>
)
}
The response inside /api/fauna/accounts returns an "after" cursor used for pagination. This is what the response looks like on the server inside /api/fauna/accounts
{
after: [
Time("2022-03-08T15:59:43.284410Z"),
Ref(Collection("accounts"), "325579003214692417"),
Ref(Collection("accounts"), "325579003214692417")
],
data: [...]
}
However, when that response is sent back to the /accounts route, the "after" cursor is formatted completely differently than on the server which makes it difficult to paginate with. The response for the "after" cursor looks like this:
{
after: [
{ "#ts": "2022-03-08T15:49:23.686204Z" },
{
"#ref": {
id: "325578353522245700",
collection: { "#ref": { id: "accounts", collection: { "#ref": { id: "collections" } } } }
}
},
{
"#ref": {
id: "325578353522245700",
collection: { "#ref": { id: "accounts", collection: { "#ref": { id: "collections" } } } }
}
}
],
data: [...]
}
How do I paginate to the next page when the "after" cursor is formated like so?
The format that you're seeing is Fauna's wire protocol. JSON doesn't handle embedded objects like References (among other complex response values), so those get serialized in a way that can be round-tripped.
The JavaScript driver includes a utility library called _json.js, which can take care of reconstituting the original cursor value:
const faunadb = require('faunadb')
const json = require('faunadb/src/_json')
const q = faunadb.query
// assuming response contains the wire protocol data from a pagination query
const deserialized = json.parseJSON(response)
// then you can include the `after` field in a subsequent query
const response2 = client.query(
q.Paginate(
q.Match(q.Index("your_index"), [<terms>]),
{
after: deserialized.after
}
)
)
.then(res => console.log(res))
.catch(err => console.err("Error:", err))

Getting a "Delivery Mode not set" for single page guest checkout

Im currently working in a project that uses the Spartacus 3.2.2 and SAP Commerce 2011 with B2C accelerator. The project doesn't follow the traditional shopping website but leverages the functionality of Spartacus and SAP Commerce for its own purposes. We have a single page guest checkout flow where the Delivery Address, Payment Details and Delivery Mode gets set with the cart when an angular component loads.
The context is that lets assume a user has a form where they enter some information like email, and some other details and click next. A cart gets generated with a sample product getting added to it and the email gets associated. The users get redirected to a page to review the information that they want to submit and this page is the single page guest checkout. When this page loads, the payment details, delivery address and delivery mode get set behind the scenes and the user will not notice anything. They click submit and they create an order behind the scenes, the frontend will show something else user when they land on the confirmation page.
The issue is that when the user submit the information after reviewing it, the order call fails and we get a "delivery mode not set" and it is INCONSISTENT.
Here is a sample code that we use for the single page guest checkout:
#Component({
selector: "review-details",
templateUrl: "./review-details.component.html",
host: { class: "template-component" },
})
export class ReviewDetailsComponent implements OnInit, OnDestroy, AfterViewInit {
hasSetAddress: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
hasSetDeliveryMode: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
hasSetPaymentDetails: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
subscriptions:any = [];
ngOnInit() {
// Just an example address. A proper valid dummy address and region is used for our project.
let address: Address = {
firstName: "No Name",
lastName: "No Name",
email: "NoName#noname.com",
line1: "XYZ Mason Street",
line2: "",
town: "yolotown",
postalCode: "12345",
country: { isocode: "US" },
defaultAddress: false,
region: {
countryIso: "US",
isocode: "US-CA",
isocodeShort: "CA",
name: "California",
},
titleCode: "",
};
let paymentDetails: PaymentDetails = {
cardNumber: "4111111111111111",
expiryMonth: "12",
expiryYear: "2025",
billingAddress: address,
cvn: "123",
accountHolderName: "No Name",
cardType: {
code: "visa",
name: "Visa",
},
defaultPayment: false,
saved: false,
};
}
this.subscriptions = this.subscriptions.concat(
{
key: 'setAddress',
value: this.checkoutDeliveryService.getDeliveryAddress().subscribe((addr: Address) => {
if (_isNil(addr) || (!_isNil(addr) && _isEmpty(addr))) {
this.checkoutDeliveryService.createAndSetAddress(address);
} else {
this.hasSetAddress.next(true);
}
})
},
{
key: 'setDeliveryModeStatus',
value: this.checkoutDeliveryService.getSupportedDeliveryModes().pipe(
withLatestFrom(
this.checkoutDeliveryService
.getSelectedDeliveryMode()
.pipe(map((deliveryMode: DeliveryMode) => deliveryMode && deliveryMode.code ? deliveryMode.code : null))
)
).subscribe(([deliveryModes, code]: [DeliveryMode[], string]) => {
if (_isNil(code)) {
if (!_isNil(deliveryModes) && !_isEmpty(deliveryModes)) {
code = this.checkoutConfigService.getPreferredDeliveryMode(deliveryModes);
if (code) {
this.checkoutDeliveryService.setDeliveryMode(code);
}
}
} else {
this.hasSetDeliveryMode.next(true);
}
})
},
{
key: 'setPaymentDetails',
value: this.checkoutPaymentService.getPaymentDetails().subscribe((paymentInfo: PaymentDetails) => {
if (_isNil(paymentInfo) || (!_isNil(paymentInfo) && _isEmpty(paymentInfo))) {
this.checkoutPaymentService.createPaymentDetails(paymentDetails);
} else {
this.checkoutPaymentService.paymentProcessSuccess();
this.hasSetPaymentDetails.next(true);
}
})
},
{
key: 'placeOrder',
value: this.checkoutService
.getOrderDetails()
.pipe(filter(order => Object.keys(order).length !== 0))
.subscribe(() => {
this.routingService.go({ cxRoute: 'orderConfirmation' });
})
}
)
}
So now the questions are:
how do we even find the root cause to this "delivery mode not set" when it is inconsistent? To give more context, the request calls for the payments, address and delivery mode are getting made correctly but when the final cart object gets returned after the requests are made, we don't have the delivery cost getting set sometimes.
Is there a way to optimize the code to rule out any race conditions that may happen? Considering that all the operations to add the payment details, address, and delivery mode are set asynchronously for the same cart.
Any help is appreciated and even optimization ideas are welcome.
Thank you
References:
Spartacus Checkout guide: https://sap.github.io/spartacus-docs/3.x/extending-checkout/#combining-checkout-steps
please refer to this SAP note for an explanation on multiple updates to checkout information using OCC API calls:
https://launchpad.support.sap.com/#/notes/2998330.
Summary: to perform various updates for checkout at the same time, you need to use a single API call. The SAP note provides an example extension you can use for this scenario.
Best regards,
Jerry
Here is the answer to my own question, thanks to the SAP Support and the Spartacus Development teams for helping me with this.
In addition to Jerry's answer which is more of a permanent and straight forward solution which would need to be done on both frontend and backend, here is another solution which only requires us to make changes on the frontend only.
The code can be changed in the following manner to make the calls sequentially load the details on the cart.
#Component({
selector: "review-details",
templateUrl: "./review-details.component.html",
host: { class: "template-component" },
})
export class ReviewDetailsComponent implements OnInit, OnDestroy, AfterViewInit {
hasSetAddress: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
hasSetDeliveryMode: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
hasSetPaymentDetails: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
subscriptions: any = [];
// Just an example address. A proper valid dummy address and region is used for our project.
private address: Address = {
firstName: "No Name",
lastName: "No Name",
email: "NoName#noname.com",
line1: "XYZ Mason Street",
line2: "",
town: "yolotown",
postalCode: "12345",
country: { isocode: "US" },
defaultAddress: false,
region: {
countryIso: "US",
isocode: "US-CA",
isocodeShort: "CA",
name: "California",
},
titleCode: "",
}
private paymentDetails: PaymentDetails = {
cardNumber: "4111111111111111",
expiryMonth: "12",
expiryYear: "2025",
billingAddress: address,
cvn: "123",
accountHolderName: "No Name",
cardType: {
code: "visa",
name: "Visa",
},
defaultPayment: false,
saved: false,
}
private address$: Observable<Address> = this.checkoutDeliveryService.getDeliveryAddress().pipe(
tap((addr: Address) => {
if (_isNil(addr) || (!_isNil(addr) && _isEmpty(addr))) {
this.checkoutDeliveryService.createAndSetAddress(this.address);
}
}),
filter((addr) => (!_isNil(addr) && !_isEmpty(addr)))
);
private deliveryMode$: Observable<string> = this.checkoutDeliveryService.getSupportedDeliveryModes().pipe(
filter((deliveryModes: DeliveryMode[]) => deliveryModes?.length !== 0),
withLatestFrom(
this.checkoutDeliveryService.getSelectedDeliveryMode()
.pipe(map((selectedDeliveryMode: DeliveryMode) => selectedDeliveryMode?.code))
),
map(([deliveryModes, code]: [DeliveryMode[], string]) => {
return code
? code
: this.checkoutConfigService.getPreferredDeliveryMode(deliveryModes);
}),
tap((code) => {
if (code) {
this.checkoutDeliveryService.setDeliveryMode(code);
}
}),
filter((code) => !!code)
);
private payment$: Observable<PaymentDetails> = this.checkoutPaymentService.getPaymentDetails().pipe(
tap((paymentInfo: PaymentDetails) => {
if (_isNil(paymentInfo) || (!_isNil(paymentInfo) && _isEmpty(paymentInfo))) {
this.checkoutPaymentService.createPaymentDetails(this.paymentDetails);
}
}),
filter((paymentInfo) => (!_isNil(paymentInfo) && !_isEmpty(paymentInfo)))
);
private setCartDetails$: Observable<boolean> = this.address$.pipe(
take(1),
map((_) => this.deliveryMode$.pipe(take(1))),
concatAll(),
map((_) => this.payment$.pipe(take(1))),
concatAll(),
map((_) => {
this.checkoutPaymentService.paymentProcessSuccess();
this.hasSetAddress.next(true);
this.hasSetDeliveryMode.next(true);
this.hasSetPaymentDetails.next(true);
return true;
}));
ngOnInit() {
this.subscriptions = this.subscriptions.concat(
{
key: "setCartDetails",
value: this.setCartDetails$.subscribe((status: boolean) => console.log(status))
},
{
key: 'placeOrder',
value: this.checkoutService
.getOrderDetails()
.pipe(filter(order => Object.keys(order).length !== 0))
.subscribe(() => {
this.routingService.go({ cxRoute: 'orderConfirmation' });
})
}
)
}
}

fetching data from API in react poll

I want to fetch data from API and show frontend using react but I am getting error from frontend side which is (TypeError: answers.map is not a function ) so how can I solve this error --
MY CODE IS -
import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import { getPolls } from "../helper/coreapicalls";
const MainPoll = () => {
const [polls, setPoll] = useState([]);
const [error, seterror] = useState(false);
// Setting answers to state to reload the component with each vote
const [pollAnswers, setPollAnswers] = useState([]);
useEffect(() => {
loadPoll();
}, []);
const loadPoll = () => {
getPolls().then((data) => {
if (data.error) {
seterror(data.error);
} else {
setPoll(data);
console.log(data);
}
});
};
// Handling user vote
// Increments the votes count of answer when the user votes
const handalchange = () => {
console.log("hello");
};
return (
<div className="">
<div className="container">
<h1 className="blog_heading">Poll's of the Day</h1>
<div className="row">
{polls.map((poll, index) => (
<div className="col-lg-4 col-12" key={index}>
<Poll
question={poll.question}
answers={poll.options.none}
onVote={handalchange}
/>
</div>
))}
</div>
</div>
</div>
);
};
export default MainPoll;
Data which I am getting from API is-
Here I have Question , 3 options how can I show to frontend
Error -
There is two little mistakes in the code that you show us:
the first One you imported import Polls from "./polls"; and you call <Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/> just change Poll by Polls.
const [pollAnswers, setPollAnswers] = useState([...answers]); this didn't work because you need to pass a initial value for your state and answer is not yet initialize and accessible. just change useState([...answers]); by useState([]);
UPDATE:
you need to pass an array to answers props .
We can see in your console screenshot that the array of options has "none" as key so
try this : <Poll noStorage question={poll.question} answers={poll.options.none} onVote={handleVote}/> ("none" is a strange key...)
UPDATE
Your data object is not well formated to fit react-polls answers props.
in the npmjs doc of react-polls we can see an example of options and it's an array of object like this:
[
{ option: 'Yes', votes: 8 },
{ option: 'No', votes: 2 }
]
so based on the data console log that you add in your question it should looks like this:
[
{
createdAt: "2020-12-01T21:43:23:21.061Z",
options: {
none: [ { option: 'Yes', votes: 8 },
{ option: 'No', votes: 2 }],
student: ["12345678978945"],
teacher: ["7894567894231"]
},
question: "Are you student ot teacher",
updatedAt: "2020-12-01T21:43:23:21.061Z"
}
]
see a sandBox here working with your code (except getPolls()).
I think the issue come from the API.

Angular 2: Load data using Server data source into my ng smart table

Has any one figure out on how to load the server data from the ng2-smart table plugin of Angular2.
I have few products data that is retrieved from Node API and Im able to display the same onClick event in the browser log.
I need to display the same in this 3rd party plugins table area which they have provided in this documentation below:
Frontend : https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server
Under "Server Data Source Example"
Code: https://github.com/akveo/ng2-smart-table/blob/master/src/app/pages/examples/server/advanced-example-server.component.ts
Accordingly i have configured in my code as below:
blank-page.component.ts
import { ServerDataSource } from 'ng2-smart-table';
import { Component } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'advanced-example-server',
template: `
<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>
`,
})
export class BlankPageComponent implements OnInit {
settings = {
columns: {
id: {
title: 'ID',
},
albumId: {
title: 'Album',
},
title: {
title: 'Title',
},
url: {
title: 'Url',
},
},
};
source: ServerDataSource;
//Doubt or Problem here!!!
constructor(http: Http) {
this.source = new ServerDataSource(http, { endPoint: 'https://jsonplaceholder.typicode.com/photos' });
}
//Tried like this too (Which is not the right way of calling)
constructor(http: Http) {
this.source = new ServerDataSource(http, { endPoint: this.productService.getProductsOncategory(this.categoryid) });
}
//Dint work this too!!
constructor(http: Http) {
this.source = new ServerDataSource(http, { endPoint:'http://localhost:5000/products/getProductsOncategory ' });
}
}
Where my service.ts file is like, which actually displays the products data in my browser log which i need to show in my table data
getProductsOncategory(category_id){
let catUrl="http://localhost:5000/products/getProductsOncategory"
let headers = new Headers();
headers.append('Content-Type','application/json');
let catIdObj = JSON.stringify({category_id:category_id})
console.log(catIdObj)
return this.http.post(catUrl,catIdObj,{headers:headers})
.map((response:Response)=>response.json())
.do(data=>console.log(JSON.stringify(data)))
.catch(this.handleError);
}
Error if i use my projects url in endpoint
Error: Uncaught (in promise): Error: Data must be an array. Please check that data extracted from the server response by the key '' exists and is array.
This is what i did and worked perfect for me, i used smart table server side paging, but build my own filter for custom filtration experience.
1- Define Server Data Source
source: ServerDataSource;
2- set it in constructor with config object
this.source = new ServerDataSource(http,
{
endPoint: 'full-url-for-endpoint',
dataKey: 'your-list-path-from-response' for example 'data.records' ,
pagerPageKey: 'your backend param excpected for page number key',
pagerLimitKey: 'your backend param excpected for page size',
totalKey: total records returned in response path for example 'data.total',
filterFieldKey: your filter keys template should set to '#field#' if you need to send params as you set, Default is '#field#_like'
});`
3- add settings object
settings = {
actions: {
custom: [ // if you need custom actions do like that
{ name: 'view-something', title: '<i title="Exception" class="nb-alert"></i>' },
{ name: 'do-custom', title: '<i class="fa fa-pencil"></i>' }
],
add: true, //if you don't need default add button set to false
edit: true, //if you don't need default add button set to false
delete: true, //if you don't need default delete button set to false
position: 'right' // buttons position
}, // remove add , edit , delete objects if you don't use
add: {
addButtonContent: '<i class="nb-plus"></i>',
createButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
edit: {
editButtonContent: '<i class="nb-edit"></i>',
saveButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
delete: {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
pager: {
display: true // set to false if no need for pagination
},
columns: {
Id: { // set up table cols - Id is a prop name returned from backend
title: 'ID', // display name in table header
type: 'number',
filter: false // add text filter for it or not
},
Name: {
title: 'Full Name',
type: 'string',
filter: false
}
}
};
// Add Filter Data , i used a custom form binded with ngModel above table for filtration, so assume you have a model called filter which get data from external form
FilterData() {
this.source.reset(true); // reset your old filtered data
this.source.setPage(1, false); // set page to 1 to start from beginning
let filterArr = this.getFilterArray(); // add a new filter data, but be careful to not sent any empty data, as it throws an exception
if (filterArr.length)
this.source.setFilter(filterArr, false, false);
this.source.refresh(); // this will call the server with new filter and paginatio data
}
getFilterArray() { // setup new filter
let filterArray = [];
if (this.filter.id)
filterArray.push({ field: 'id', search: this.filter.id });
if (this.filter.name)
filterArray.push({ field: 'name', search: this.filter.name});
return filterArray;
}
onCustomAction(event) { // custom buttons code
switch (event.action) {
case 'view-something':
// put your code here
break;
default:
console.log('Not Implemented Action');
break;
}
}
With this example my data is resource so the datakey is set resource
find below sample code
{
source: ServerDataSource;
constructor(http: HttpClient) {
this.source = new ServerDataSource(http, { dataKey: 'resource', endPoint:'http://localhost:8080/api/v2/mysql/_table/able' })
}
You need to set the dataKey for the ServerDataSource. For example, if your JSON is { data: [...], total: .. }, you need to set dataKey = 'data'.
this worked for me on Angular 8, But Search box functionality needs to be handeled from backend (i.e: localhost:5000/session_info/Seance1?temp_like=30), so backend need to filter (temp_like = value) in database, which make search box retrive live data.
Here is the entire component with Edit and Delete, Enjoy it!
import {Component} from '#angular/core';
import {ServerDataSource} from 'ng2-smart-table';
import {HttpClient} from "#angular/common/http";
import {Setting} from "../../setting";
#Component({
selector: 'ngx-session-man',
templateUrl: './sessions-man.component.html',
styleUrls: ['./sessions-man.component.scss'],
})
export class SessionsManComponent {
settings = {
mode: 'inline',
add: {
addButtonContent: '<i class="nb-plus"></i>',
createButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
edit: {
editButtonContent: '<i class="nb-edit"></i>',
saveButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
confirmSave: true,
},
delete: {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
columns: {
name: {
title: 'Séance',
type: 'string',
},
start: {
title: 'Début',
type: 'any',
},
end: {
title: 'Fin',
type: 'any',
},
},
};
source: ServerDataSource;
constructor(private httpClient: HttpClient) {
this.source = new ServerDataSource(this.httpClient, {endPoint: Setting.baseUrl + 'all_sessions_table'});
}
onDeleteConfirm(event): void {
if (window.confirm('Are you sure you want to delete ' + event['data']['name'] + '?')) {
event.confirm.resolve();
this.httpClient.delete<any>('http://localhost:5000/del-seance/' + event['data']['name']).subscribe(
temps => {});
} else {
event.confirm.reject();
}
}
onEditConfirm(event): void {
if (window.confirm('Are you sure you want to edit ' + event['data']['name'] + '\'s name to ' + event['newData']['name'] + '?')) {
event.confirm.resolve();
this.httpClient.post<any>('http://localhost:5000/mod-seance/' + event['data']['name'] + '/' + event['newData']['name'], { title: 'Session deleted' }).subscribe(
temps => {});
} else {
event.confirm.reject();
}
}
}

Resources