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.
Advertisement
Answer
[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.