What is the best way to integrate ag-grid with Observable in Angular 2?

After conducting extensive research on the Internet, I am still struggling to connect the pieces. My angular2 application utilizes an Observable data source from HTTP and I am attempting to integrate ag-grid. However, all I see is a loading screen instead of the expected data. Upon examining with Fiddler, it appears that the data is being successfully loaded in JSON format. Below is my code:

order.service.ts

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { Observable }    from 'rxjs/Observable';

import { Order } from './order';

@Injectable()
export class OrderService {

  private ordersUrl = '(Some JSON data source via Internet)';  // URL to web api

  constructor(private http: Http) { } 

  getOrders(): Observable<Order[]> {
    return this.http.get(this.ordersUrl)
        .map(this.extractData)
        .catch(this.handleError);
  }

  save(order: Order): Observable<Order>  {
    if (order.id) {
      //return this.put(order);
    }
    return this.post(order);
  }

  delete(order: Order) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let url = `${this.ordersUrl}/${order.id}`;

    return this.http
       .delete(url, headers)
       .map(this.extractData)
       .catch(this.handleError);
  }

  // Add new Order
  private post(order: Order): Observable<Order> {
    let headers = new Headers({
      'Content-Type': 'application/json'});

    return this.http
               .post(this.ordersUrl, JSON.stringify(order), {headers: headers})
               .map(this.extractData)
               .catch(this.handleError);
  }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
    }

    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

order.component.ts

import { Component, OnInit } from '@angular/core';
import { Router }            from '@angular/router';

import { AgGridNg2 } from 'ag-grid-ng2/main';

import { Order }                from './order';
import { OrderService }         from './order.service';


@Component({
  selector: 'my-orders',
  templateUrl: 'app/order/order.html',
  directives: [ AgGridNg2 ]
})

export class OrderComponent implements OnInit {
    errorMessage: string;
    orders: Order[];
    selectedOrder: Order;
    addingOrder = false;
    error: any;
    mode = 'Observable';
    gridOptions: any = [];

    ngOnInit() {
        this.getOrders();
    }

    columnDefs = [(Some definition)];

    getOrders() {
        this.orderService
            .getOrders()
            .subscribe(
               orders => this.orders = orders,
               error =>  this.errorMessage = <any>error);
    }

    constructor(
        private router: Router,
        private orderService: OrderService) {
            orderService
                .getOrders()
                .subscribe(
                   orders => this.orders = orders,
                   error =>  this.errorMessage = <any>error);

                this.gridOptions = {
                    rowData: this.orders,
                    columnDefs: this.columnDefs,
                    enableColResize: true,
                    enableSorting: true,
                    enableFilter: true
                }
        }

    onSelect(order: Order) {
        this.selectedOrder = order;
        this.addingOrder = false;
    }
}

The above code has been adapted from a Google tutorial for illustrative purposes only.

Here is the HTML file, containing one tag for ag-grid:

<ag-grid-ng2 #agGrid style="width: 100%; height: 350px;" class="ag-fresh" [gridOptions]="gridOptions">
</ag-grid-ng2>

I appreciate any assistance you can provide. Thank you for potentially saving me here.

Answer №1

Your implementation using Observable appears to be correct, but you need to bind the orders to the grid:

<ag-grid-ng2 
    #agGrid 
    style="width: 100%; height: 350px;" 
    class="ag-fresh" 

   [gridOptions]="gridOptions"
   [rowData]="orders">
</ag-grid-ng2>

Another approach would be to set the gridOptions within the subscribe callback:

    private orderService: OrderService) {
        orderService
            .getOrders()
            .subscribe(
                orders => { 
                    this.orders = orders;

                    this.gridOptions = {
                        rowData: this.orders,
                        columnDefs: this.columnDefs,
                        enableColResize: true,
                        enableSorting: true,
                        enableFilter: true
                    };
                },
                error =>  this.errorMessage = <any>error
            );
    }

Check out this Github Repository for more examples on utilizing ag-grid-ng2.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

Tips for handling numerous buttons in ionic?

I'm currently working on an app that includes surveys. In this app, users are required to answer by selecting either the Yes or No button. The desired behavior is for the chosen button to turn blue once clicked, while the other button should maintain ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

I'm encountering an issue with my launch.json file where an error is being triggered on the line that contains "program": "${workspaceFolder}\serve". What could be causing this error?

Whenever I attempt to start the debugger for my Angular application, I encounter the following error message: "Attribute 'program' does not exist ('C:\repos\recipes\serve') I have already attempted to remove the pre-exi ...

Techniques for concealing a button when the "disabled" attribute is set to "true"

The button is currently disabled, however, I intended for it to be hidden from the UI when the disabled condition is met - <button ion-button block class="button-color-blue" [disabled]="true" (click)="closePage()"> Cancel </b ...

Tips for personalizing the ngx-bootstrap datepicker

I am looking to enhance the ngx-bootstrap datepicker popup by adding a link or button within the calendar to select dates with a single click. I have been exploring ways to customize the datepicker without success. Currently, my project is built using Angu ...

Unable to perform the upgrade to Angular 6 due to an invalid range

I'm in the process of upgrading to Angular 6 As I follow the upgrade guide, I run into this issue: > ng update @angular/core Invalid range: ">=2.1.0" That's all the information I have. There are no additional warnings or ...

Encountering issue when attempting to reset stepper component in angular

In my current project, I am implementing an angular stepper with two screens. If a user navigates back to step 1 by clicking the back button or directly on a label, I want to reset the stepper using the reset() function. However, when I attempt to navigate ...

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

A Project built with React and TypeScript that includes code written in JavaScript file

Is it an issue when building a React project with Typescript that includes only a few JS components when moving to production? ...

A Unique Identifier in Kotlin

In my typescript class, I have a member that accepts any as the name: interface ControlTagType { type?: String | null; [name: string]: any } class ControlTag { tagSource: String | null = null; tag: ControlTagType | null = null; } expor ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...

Tips for stopping webpack from creating compiled files in the source directory

I'm in the process of transitioning my AngularJs project from ES6 to TypeScript and I've integrated webpack with ts-loader. However, I've encountered an issue where the compiled files and source maps are saved in my directory instead of bei ...

What are the best ways to personalize my code using Angular Devextreme?

Our development team is currently utilizing Angular for the front-end framework and ASP.net for the back-end framework. They are also incorporating Devextreme and Devexpress as libraries, or similar tools. However, there seems to be difficulty in implement ...

How can I incorporate a feature in my Angular application that allows users to switch between different view types, such as days, using JavaScript

Greetings, community! I am currently utilizing version 5 of the fullcalendar library from https://fullcalendar.io/ in my Angular 9 application. I have noticed that the calendar offers various options to change the view type as shown below: https://i.stac ...

How to update the tsconfig.json file within a VS2019 project using MSBuild?

I am working with a Visual Studio solution that contains multiple tsconfig.json files and I would like them to have different behaviors in production. My plan is to create two additional files for this purpose: tsconfig.json will contain the default sett ...

Customizing Tabs in Material UI v5 - Give your Tabs a unique look

I am attempting to customize the MuiTabs style by targeting the flexContainer element (.MuiTabs-flexContainer). Could someone please clarify the significance of these ".css-heg063" prefixes in front of the selector? I never noticed them before upgrading my ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...