0

I have installed an angular 2 library in my application called "angular2-grid". This library is placed under node_modules folder.

I have built a service like 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);

}
  // some other code here

NgGridConfig is an interface as below

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;
}

For some of these properties I have put some values on gridCongig.json file

In my component I have the code below:

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; 


 }

Now when I run this application I got at 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}]

That means that the serivice is called and the json file is called and mapped properly because do method gives the desired output.

The problem I assume it is with my subscribe since property ngGridConfig of type NgGridConfig is still empty. I realize that after I put a console.log(this.ngGridConfig.min_rows) and the result is undefined.

I need some help how can my property ngGridConfig to take all the values mapped from the service?

n00dl3
  • 21,213
  • 7
  • 66
  • 76
Dea
  • 291
  • 3
  • 6
  • 17
  • 1
    where di you put you `console.log()` ? – n00dl3 Apr 05 '17 at 13:09
  • your subscribe() looks fine, but keep in mind that Observables are asynchronous, so the handler method you're passing will be called only when actual data is available. If you're trying to log the value of `ngGridConfig` to the console right after calling `subscribe()`, you will not get what you expect – David M. Apr 05 '17 at 13:11
  • Most likely a dupe of http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 But yet to mark it as one, since the placement of the console.log is still unclear ;) – AT82 Apr 05 '17 at 13:15
  • @DavidM. Even if i put console.log right after calling subscribe I still got undefined value. I guess maybe this has to do with the fact that NgGridConfig is an interface built by angular-grid which is located in node_modules folder. I have a lot of other services and all of them are working great – Dea Apr 05 '17 at 13:20
  • @AJT_82 Aaaaaand.... That's a dupe ! – n00dl3 Apr 05 '17 at 13:20
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – n00dl3 Apr 05 '17 at 13:21

1 Answers1

0

I think _generateDefaultDashConfig method use this.ngGridConfig so you have to wait until the getWidgets resolves:

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;
                          this.doConfig()
                          },
                      error => this.errorMessage = <any>error);
   }
}  

doConfig(){
     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; 


}
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37