The subscription function in observables may result in values that are undefined

I integrated a new angular 2 library into my application called "angular2-grid". This library is located within the node_modules folder.

Furthermore, I created a service as shown below:

 import { Injectable } from '@angular/core';
 import { Http, Response } from '@angular/http';
 import { Observable } from 'rxjs/Observable';
 import 'rxjs/add/operator/map';
 import 'rxjs/add/operator/do';
 import 'rxjs/add/operator/catch';

 import {NgGrid, NgGridItem, NgGridConfig, NgGridItemConfig, NgGridItemEvent} from 'angular2-grid';


 @Injectable()
 export class WidgetService {

private _widgetUrl = './assets/gridConfig.json';

constructor(private _http: Http) { }

getWidgets(): Observable<NgGridConfig> {

    return this._http.get(this._widgetUrl)
        .map(res=>res.json())
        .do(data => console.log("All: " + JSON.stringify(data)))
        .catch(this.handleError);

}
  // additional code can be placed here

The interface for NgGridConfig is defined as follows

export interface NgGridConfig {
margins?: number[];
draggable?: boolean;
resizable?: boolean;
max_cols?: number;
max_rows?: number;
visible_cols?: number;
visible_rows?: number;
min_cols?: number;
min_rows?: number;
col_width?: number;
row_height?: number;
cascade?: string;
min_width?: number;
min_height?: number;
fix_to_grid?: boolean;
auto_style?: boolean;
auto_resize?: boolean;
maintain_ratio?: boolean;
prefer_new?: boolean;
zoom_on_drag?: boolean;
limit_to_screen?: boolean;
}

I have set values for some properties in the gridCongig.json file

In my component, the following code is implemented:

import { Component, ViewEncapsulation,OnInit } from '@angular/core';
import {NgGrid, NgGridItem, NgGridConfig, NgGridItemConfig, NgGridItemEvent}   from 'angular2-grid';
import {IBox} from './grid'
import {WidgetService} from './grid.service'

@Component({
 templateUrl: './grid.component.html',
 styleUrls: ['./grid.component.css'],
 })


export class GridComponentDemo {

private boxes: Array<IBox> = [];
private rgb: string = '#efefef';
private curNum;
imageWidth: number= 50;
imageMargin: number=2;
widgets:  Array<IWidgets> = [];
errorMessage: string;
private itemPositions: Array<any> = [];
ngGridConfig : NgGridConfig;

constructor (private _widgetService: WidgetService) {



  }

ngOnInit(): void {

 this._widgetService.getWidgets()
                      .subscribe(ngGridConfig=>this.ngGridConfig=ngGridConfig,
                      error => this.errorMessage = <any>error);


 const dashconf = this._generateDefaultDashConfig(); 

    for (var i = 0; i < dashconf.length; i++) { //6
        const conf = dashconf[i]; 
        conf.payload = 1 + i;
        this.boxes[i] = { id: i + 1, config: conf,name: "widget " + conf.payload + " :"};
    }

    this.curNum = dashconf.length + 1; 


 }

Upon running the application, the following output is displayed in the console

All: [{"margins":[5],"draggable":true,"resizable":true,"max_cols":0,"max_rows":0,"visible_cols":0,"visible_rows":0,"min_cols":1,"min_rows":1,"col_width":2,"row_height":2,"cascade":"up","min_width":50,"min_height":50,"fix_to_grid":false,"auto_style":true,"auto_resize":false,"maintain_ratio":false,"prefer_new":false,"zoom_on_drag":false,"limit_to_screen":true}]

This indicates that the service call and json file mapping are functioning correctly due to the desired output obtained from the do method.

However, it seems there may be an issue with the subscribe function since the property ngGridConfig of type NgGridConfig remains empty. This was identified when inspecting the value using

console.log(this.ngGridConfig.min_rows)
resulting in undefined.

I am seeking assistance on how to ensure that my property ngGridConfig retrieves all the mapped values from the service?

Answer №1

In my opinion, the _generateDefaultDashConfig function utilizes this.ngGridConfig, so it is necessary to wait for the resolution of the getWidgets method:

export class GridComponentExample {

private elements: Array<Element> = [];
private color: string = '#abcdef';
private num;
thumbnailWidth: number= 70;
thumbnailMargin: number=5;
widgetsList:  Array<WidgetElement> = [];
errorText: string;
private positions: Array<any> = [];
ngGridConfiguration : NgGridConfiguration;

constructor (private _widgetService: WidgetService) {



  }

ngOnInit(): void {

    this._widgetService.getWidgets()
                      .subscribe(ngGridConfiguration=>{
                         this.ngGridConfiguration=ngGridConfiguration;
                          this.configureLayout()
                          },
                      error => this.errorText = <any>error);
   }
}  

configureLayout(){
     const configuration = this._generateDefaultDashConfig(); 

    for (var j = 0; j < configuration.length; j++) { //6
        const setting = configuration[j]; 
        setting.data = 1 + j;
        this.elements[j] = { id: j + 1, config: setting,name: "item " + setting.data + " : "};
    }

    this.num = configuration.length + 1; 


}

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

Discover the unique value in Angular if it is not present in the list

I have a question about handling values in a list and displaying the "create value" component to the user when needed. How can I efficiently compare search input values with those in the list and determine if a match exists? If no match is found, the "cr ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

TS2349 emerges when incorporating lazy-loading in React

I've been working on refactoring a React 18 app to incorporate lazy loading, following the guidelines provided in the official documentation: One effective method to implement code-splitting in your application is through the dynamic import() syntax ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

How to showcase the data retrieved via BehaviorSubject in Angular

I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen: Here is the service code snippet: @Injectable({ providedIn: 'root', }) export clas ...

Using Angular in conjunction with Azure Durable Functions to implement a retry mechanism for HTTP responses

In my Angular 10 application, I am attempting to integrate Azure Functions. The key is to simplify the Azure function protocol by using a single Observable. Executing an Azure function requires the following steps: Initiate a POST request to the Azure fu ...

Optimizing row performance for Angular grids in the Chrome browser

When creating a component that includes a table with numerous rows, everything works well with small amounts of data. However, once the item count reaches 2000 or more, it starts lagging. Scrolling and animations become sluggish. Even after trying to impl ...

Exciting new venture utilizing Angular version 15 in combination with the latest Firebase 9

Recently, I set up node version 18.10.0 and attempted to start a fresh Angular 15 project using Firebase 9 for hosting, Firestore database, and authentication. However, after running the commands below, I noticed that the @angular/fire directory was missin ...

Angular 6 - Accessing grandparent methods in grandchild components

I am in need of running the functions of the grandparent component: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.cs ...

Typescript Code Coverage with karma-jasmine and istanbul: A complete guide

I am attempting to calculate the Code Coverage for my typescript Code in karma framework using Istanbul. In the karma.conf file, typescript files are added and through karma typescript-preprocessor we are able to conduct unit testing and code coverage of t ...

Narrowing Down State Types

I am working on a functional component in NextJS with props passed from SSR. The component has a state inside it structured like this: const MyComponent = ({err, n}: {err?: ErrorType, n?: N})=>{ const [x, setX] = useState(n || null) ... if(e ...

Challenges encountered while developing Angular FormArrays: Managing value changes, applying validators, and resolving checkbox deselection

I am facing an issue with my Angular formArray of checkboxes. In order to ensure that at least one checkbox is selected, I have implemented a validator. However, there are two problems that I need to address: Firstly, when the last checkbox is selecte ...

Troubleshooting a GET Request Hanging Issue with Next.js 13 Route Handler

I'm currently encountering an issue with the new routing feature in my Next.js 13 project. I have a route handler set up in app/api/ingresos/route.ts with the code snippet below: import { NextResponse } from 'next/server'; import PocketBase ...

Difficulty in styling with ag-Grid in SharePoint Framework (SPFX) combined with Angular

I'm currently delving into the world of custom SharePoint Web Parts using SharePoint Framework (SPFX) in combination with Angular Elements. One roadblock I've encountered is that when trying to implement ag-Grid, the style definitions for the gri ...

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Tips for customizing the list of components and attributes for each component in the Angular Form.io builder

I have successfully integrated form.io with Angular 10. After creating a demo project using form.io in the Angular CLI, I was able to develop a custom component and customize the editForm for it. import { Injector } from '@angular/core'; import ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

Make sure to name your Typescript component selector correctly, as it should not

As I work on my Angular project, I encountered a situation where one component needed to be referenced in the HTML of another component. To make this connection, I used kebab case for the selector like so: @Component({ selector: 'swiftlog-navbar&ap ...

Angular 7 with JQWidgets - How to Export Grid data from a different component

Currently, I am working on integrating Angular 7 with JQWidgets. My focus is on the Grid component and my goal is to export data from the Grid in another component called settings. I followed a demo (accessible here) and created the component below: impor ...

Altering the properties of a specified element within TestBed using the overrideComponent method

We are implementing TestBed.overrideComponent() to substitute a component with custom behavior. TestBed.overrideComponent(CoolComponent, { set: { template: '<div id="fake-component">i am the fake component</div>', sel ...