How to fetch data from API in ng2 smart table? - javascript

I have an angular app using Ng2 smart table and need to fetch data from API I create a method to fetch data from API (but I didn't know it works or not ) and the main problem is how to get data to show in ng2 smart table
Following is my HTML code
<div class="mainTbl">
<ng2-smart-table [settings]="settMain" [source]="dataMain"></ng2-smart-table>
</div>
my service .ts
#Injectable({
providedIn: 'root'
})
export class ClientsService {
url="http://localhost:21063/api/clints"
clients:Clients[];
constructor(private http:HttpClient) { }
getAllClients(){
this.http.get(this.url).toPromise().then(
res=>{
this.clients = res as Clients[];
}
)
}
}
component .ts :
export class ClientInfoComponent implements OnInit {
// start main stores tbl
settMain = {
noDataMessage: 'عفوا لا توجد بيانات',
actions: {
columnTitle: 'إجراءات',
position: 'right',
},
pager: {
perPage: 25,
},
add: {
addButtonContent: ' إضافة جديد ',
createButtonContent: '',
cancelButtonContent: '',
},
edit: {
editButtonContent: '',
saveButtonContent: '',
cancelButtonContent: '',
},
delete: {
deleteButtonContent: '',
},
columns: {
index: {
title: 'مسلسل',
width: '80px',
},
id: {
title: 'كود العميل',
width: '80px',
},
name: {
title: 'اسم العميل',
width: '160px'
},
phone: {
title: ' الهاتف'
},
address: {
title: ' العنوان'
},
nots: {
title: 'ملاحظات'
}
}
};
dataMain = [
{
index:1,
id:"",
name: "",
phone:"",
address: "",
nots: "",
}
];
// end main stores tbl
private myForm: FormGroup;
constructor(private formBuilder: FormBuilder,private Service:ClientsService) { }
ngOnInit() {
this.Service.getAllClients();
}
so I need some help to get data and how to but it in component .ts dataMain array, thanks in advance and excuse me because I'm a beginner.

[source]="dataMain" from your html template needs to be set to whatever Array you are fetching from the API.
I'm assuming you want your Client data to show, as the function
getClientData() appears to be returning an array of clients:
getAllClients(){
this.clients = this.http.get(this.url).toPromise().then(
res=>{
// you assigned the array to the value this.clients below
this.clients = res as Clients[];
}
)
}
your HTML settings should have [source]="this.clients" instead of dataMain, since this.clients is the variable that holds the list you want to show.

public getclients():Observable<any[]> {
return this.http.get<any[]>(this.url)
.pipe(
//catchError(this.handleError<client[]>('getclients', []))
// catchError(this.handleError)
);
}

Related

How to implement object from other one

I'm learning Javascript by myself. I work with Vuejs & express on a CRUD App.
On a component, I request my back-end trough my api : localhost:3000/api/transport
Response give me all objects from the db.
With this response I want to implement an object to make a calendar using vue-val component.
This is my component script :
<script>
import VueCal from 'vue-cal'
import 'vue-cal/dist/vuecal.css'
import axios from 'axios'
export default {
components: { VueCal },
data() {
return {
transport: [],
events: [
/*{
start: '2021-01-21 10:30',
end: '2021-01-21 11:30',
title: 'Rdv dentiste',
content: '<i class="v-icon material-icons">local_hospital</i>',
class: 'health'
},*/
],
};
},
mounted() {
this.getTransport();
},
methods: {
getTransport: function() {
this.loading = true;
axios.get('http://127.0.0.1:3000/api/transport/')
.then((response) => {
this.transport = response.data;
this.implementEvents(this.transport);
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},
implementEvents: function(transports) {
for(var transport in transports) {
console.log(transport.id)
this.events.push({
start: transport.startDate,
end: transport.endDate,
title: transporte.designation
})
}
}
}
};
</script>
implementEvents function take my response on parameter but I don't know why don't implement events array.
If I replace with code below, it's work.
implementEvents: function(transports) {
for(var transport in transports) {
console.log(transport.id)
this.events.push({
start: '2021-01-21 10:30',
end: '2021-01-21 10:30',
title: 'test'
Anyone have an idea ?
Try using forEach instead of for-in
implementEvents: function(transports) {
trnsports.forEach(transport => {
console.log(transport.id)
this.events.push({
start: transport.startDate,
end: transport.endDate,
title: transporte.designation
})
})
}

How to get info stored in the state of the store.js in vue?

I am developing my first application in vuejs.
It's a form with several steps that share a header and a footer and as I go along I send to the store.js the info I'm putting in each section.
I have been stuck for a couple of days in the fact that I am not able to retrieve the info from the first sections of the form to be able to show a summary of the info entered in the last step.
In each step every time I click on the advance button I send the info to store.js and I navigate to the next component.
This would be an example of the action in one of the components
onSubmit() {
const formData = {
selectedService: this.focusService,
selectedItem: this.selectedItem,
selectedShop: this.selectedShop,
selectedItemId: this.selectedItemId
};
this.$store.dispatch('formInfo', {
selectedService: formData.selectedService,
selectedItem: formData.selectedItem,
selectedShop: formData.selectedShop,
selectedItemId: formData.selectedItemId
});
this.$store.dispatch('setStep', this.step + 1)
this.$router.push('/shop/buyer')
},
In the store.js I check that the info arrives correctly in the 'formInfo()' method and I save it in a declared state class property and I set up a get of the info stored in the state.
export default new Vuex.Store({
state: {
step: 0,
idToken: null,
items: null,
shops: null,
estimations:null,
owner: {
ownerCivility: '',
ownerLastname: '',
ownerFirstname: '',
ownerAddressFirstLine: '',
ownerAddressSecondLine: '',
ownerAddressThirdLine: '',
ownerPostalCode: '',
ownerCity: '',
ownerPhone: '',
ownerEmail: '',
country: 'FR'
},
fisrtStepInfo: {
}
},
actions: {
formInfo({commit, dispatch}, authData) {
console.log(authData)
this.fisrtStepInfo = authData
console.log(this.fisrtStepInfo)
}
},
getters: {
formInfoFirstStep (state) {
console.log(state)
return state.fisrtStepInfo
}
}
Finally, in the component where I want to show that info in my html, I set in the 'computed' section of my script the call to getter previously declared in the store.js.
export default {
data() {
return {
step: 2,
civil: '',
name: '',
lastName: '',
email: '',
adresse: '',
phone: '',
postalCode: '',
submitted: false,
}
},
components:{
},
computed: {
firstFormInfo() {
console.log('firstforminfo')
return !this.$store.getters.formInfoFirstStep
},
}
}
</script>
But at this point, it doesn't even go through the getter in my 'computed' section.
What am I doing wrong?
Thank you in advance for your time and help.
Actions are similar to mutations, the differences being that: Instead of mutating the state, actions commit mutations.
You need to commit a mutation instead of directly altering state:
state: {
...
fisrtStepInfo: {}
},
mutations: {
setStepInfo: (state, data) => state.fisrtStepInfo = data;
}
actions: {
formInfo({commit, dispatch}, authData) {
console.log(authData)
commit('setStepInfo', authData)
console.log(this.fisrtStepInfo)
}
},
getters: {
formInfoFirstStep (state) {
console.log(state)
return state.fisrtStepInfo
}
}

dat.GUI and Complex Variables

I'm fairly new to dat.GUI and I'm having problems getting it to work with a more complex variable.
I have the following:
let complexVariable= {
topLayer:
{
deeperLayer:
{
deepestLayer: 20,
//Other stuff
}
}
}
let gui = new dat.GUI();
gui.add(complexVariable, "topLayer.deeperLayer.deepestLayer", 10, 40);
This gives me the following error:
Uncaught Error: Object "[object Object]" has no property "topLayer.deeperLayer.deepestLayer"
Any help here would be appreciated.
It currently doesn't seem possible by looking at the source code. They use bracket notation with the single property you pass in on the object.
function add(gui, object, property, params) {
if (object[property] === undefined) {
throw new Error(`Object "${object}" has no property "${property}"`);
}
...
So what you are telling dat.GUI to do is find a top level property "topLayer.deeperLayer.deepestLayer" and that obviously does not exist on your object. It seems like more code would have to be written to support nested properties.
dat.gui would have to do something like if (object[property1][property2][...] === undefined) or in your case - complexVariable["topLayer"]["deeperLayer"]["deepestLayer"];
It's obvious that question is ~4 years old. But I was searching for the same and I found your question before realizing that it's possible. Below is E2E sample in Angular.
import { AfterViewInit, Component, ViewChild, ViewContainerRef } from '#angular/core';
import { GUI, GUIController, GUIParams } from 'dat.gui';
export type EditorMetadata = Array<IEditorFolder>;
export interface IDatState {
state: EditorMetadata;
instance: GUI;
metadata: EditorMetadata;
}
export interface IEditorFolder {
title: string;
property?: string;
tooltip: string;
elements?: Array<IEditorElement>;
folders?: Array<IEditorFolder>;
folderRef?: GUI;
}
export interface IEditorElement {
title: string;
tooltip: string;
options?: any;
elementRef?: GUIController;
target?: Object;
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
#ViewChild('container', { read: ViewContainerRef, static: true })
container: ViewContainerRef;
constructor() { }
ngAfterViewInit(): void {
this.composeEditor(this.container.element.nativeElement, options, foldersMetadata);
}
composeEditor(container: HTMLElement, editorOptions: GUIParams, editorMetadata: EditorMetadata): IDatState {
const
addFolder = (folder: IEditorFolder, parent: GUI): GUI => {
const
{ title, tooltip } = folder,
folderController = parent.addFolder(title);
folderController.domElement.setAttribute('title', tooltip);
return folderController;
},
addElement = (folder: GUI, element: IEditorElement, target: Object): GUIController => {
const
{ title, options, tooltip } = element,
elmController = folder
.add(target, title, options)
.name(title)
.onChange((value) => {
console.log(model);
});
elmController.domElement.setAttribute('title', tooltip);
return elmController;
},
createDat = (options: GUIParams, metadata: EditorMetadata): IDatState => {
const
state: IDatState = {
instance: new GUI(options),
state: JSON.parse(JSON.stringify(metadata)), // Don't touch original metadata, instead clone it.
metadata: metadata, // Return original metadata
};
return state;
},
process = (folders: EditorMetadata, parent: GUI, model: Object): void => {
folders.forEach(folder => {
const target: Object = folder.property ? model[folder.property] : model; // Root level or object nested prop?
folder.folderRef = addFolder(folder, parent);
folder.elements && folder.elements.forEach(element => element.elementRef = addElement(folder.folderRef, element, target));
folder.folders && process(folder.folders, folder.folderRef, target);
});
},
{ state, instance, metadata } = createDat(editorOptions, editorMetadata);
process(state, instance, model);
container.appendChild(instance.domElement);
return { state, instance, metadata };
}
}
const options: GUIParams = {
hideable: false,
autoPlace: false,
closeOnTop: false,
width: 250,
name: 'DAT Sample'
};
const model = {
rtl: true,
renderer: 'geras',
theme: 'dark',
toolbox: 'foundation',
toolboxPosition: 'left',
debug: {
alert: false
}
};
const foldersMetadata: EditorMetadata = [
{
title: 'Options',
tooltip: 'Options AA',
elements: [
{
title: 'rtl',
tooltip: 'RTL',
},
{
title: 'renderer',
tooltip: 'Renderer',
options: ['geras', 'thrasos', 'zelos']
},
{
title: 'theme',
tooltip: 'Theme',
options: ['classic', 'dark', 'deuteranopia', 'tritanopia', 'highcontrast']
},
{
title: 'toolbox',
tooltip: 'Toolbox',
options: ['foundation', 'platform', 'invoice']
},
{
title: 'toolboxPosition',
tooltip: 'Toolbox Position',
options: ['left', 'right', 'top', 'bottom']
},
],
folders: [
{
title: 'Debug',
property: 'debug',
tooltip: 'Debug mode',
elements: [
{
title: 'alert',
tooltip: 'Alert Tooltip',
},
]
}
]
},
];

Data Binding with Smart table from json file

i want to bind the json file to a smart table. How to use the loop function for the iteration.. please help
It only shows the design of smart table.
didn't binding the data from json
this is the json file
[
{
"year": 2013,
"id": "",
"doctor": "Dr. Smith",
"illness": "Flu",
"apptdate": "3/12/2013",
"details":"Patient had flu for 5 days. No medicines prescribed"
}
]
i used to retrieve data using
#Injectable()
export class SmartTablesService {
constructor(private http: Http) {
}
smartTableData = [];
loadData() {
console.log('loadData');
this.http.get('http://192.168.0.100:8000/medical')
.subscribe((data) => {
setTimeout(() => {
var contactData = [];
$.each(data.json(), function (key, value) {
var tempData = value.source;
contactData.push(tempData);
});
this.smartTableData = contactData;
}, 1000);
});
}
getData(): Promise<any> {
console.log("Promise");
this.loadData();
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(this.smartTableData);
resolve(this.smartTableData);
}, 3000);
});
}
}
constructor(private http: Http) { }
getComments() {
return this.http.get('http://192.168.0.100:8000/article' )
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error));
}
}*/
this is the component part
#Component({
selector: 'new',
template: '<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>'
})
export class NewComponent {
query: string = '';
settings = {
noDataMessage: 'Loading...',
columns: {
year: {
title: 'YEAR',
type: 'string'
},
id: {
title: 'ID',
type: 'string'
},
doctor: {
title: 'DOCTOR',
type: 'string'
},
illness: {
title: 'ILLNESS',
type: 'string'
},
apptdate: {
title: 'APPTDATE',
type: 'string'
},
details: {
title: 'DETAILS',
type: 'string'
}
}
};
// data
source: LocalDataSource = new LocalDataSource();
constructor(protected service: SmartTablesService){
this.service.getData().then((data) => {
this.source.load(data);
});
}
}
please anyone anyone know how to bind it ..help
simply change the subscribe part in the service page to
var tempData = value;
so .subscriber looks like
.subscribe((data) => {
setTimeout(() => {
var contactData = [];
$.each(data.json(), function (key, value) {
var tempData = value; contactData.push(tempData);
});
this.smartTableData = contactData;
}, 1000);
});
}
it works..!

Pass object to Angular2 Component using Router

I'm poking Angular2 and it's Routing system. I'm creating 'Project Wizard' #Component with 'child' #Components using #RouteConfig and it looks like this:
const enum State {
welcome, basicData, groupsData, overview
}
const enum Condition {
back
}
#Component({
selector: 'router-outlet',
templateUrl: '/app/templates/wizard/project/project-wizard-container.html',
directives: [
ROUTER_DIRECTIVES,
],
})
#RouteConfig([
{ path: '/', name: 'ProjectWizardWelcome', component: ProjectWizardWelcomeComponent, useAsDefault: true },
{ path: '/step2', name: 'ProjectWizardStep2', component: ProjectWizardStep2Component },
{ path: '/step3', name: 'ProjectWizardStep3', component: ProjectWizardStep3Component },
{ path: '/overview', name: 'ProjectWizardOverview', component: ProjectWizardOverviewComponent },
])
export class ProjectWizardComponent {
mock: Mock = new Mock();
private mapping: {key: State, value: string}[] = [
{ key: State.welcome, value: 'ProjectWizardWelcome' },
{ key: State.basicData, value: 'ProjectWizardStep2' },
{ key: State.groupsData, value: 'ProjectWizardStep3' },
{ key: State.overview, value: 'ProjectWizardOverview' },
];
private transitions: FSM.Transition<State, Condition>[] = [
{ from: State.welcome, conditions: [], to: State.basicData },
{ from: State.basicData, conditions: [Condition.back], to: State.welcome },
{ from: State.basicData, conditions: [], to: State.groupsData },
{ from: State.groupsData, conditions: [Condition.back], to: State.basicData },
{ from: State.groupsData, conditions: [], to: State.overview },
{ from: State.overview, conditions: [Condition.back], to: State.groupsData },
];
private fsm: FSM<State, Condition> = new FSM(State.welcome, this.transitions);
constructor(
private _router: Router,
private _routeParams: RouteParams) {
}
onPrev(): void {
var prevState = this.fsm.apply([Condition.back]).get();
var prevRoute = this.mapping[prevState].value;
this._router.navigateByInstruction(this._router.generate([prevRoute]), true);
}
onNext(): void {
var nextState: State = this.fsm.apply([]).get();
var nextRoute = this.mapping[nextState].value;
this._router.navigateByInstruction(this._router.generate([nextRoute]), true);
}
onCancel(): void {
this._router.navigate(['Welcome']);
}
}
I need to share a Mock object across 'child' components and I want to understand what my options are. My current understanding is that:
it can be shared using container object which is #Injectable like some Service.
using RouterData. In this case, I would need to unmarshal data from url.
But are there any other ways to pass this object to #Components directly using router?
No, these two are the available options. I'd suggest a shared service.

Categories