2

Here InDynamicDatabase class I fetch value from server and got In console.log(this.rootLevelNodes) // folder-1 folder-2 folder-3 folder-4 see In below code but I want this value in array. and then outside this.route I print console.log(this.rootLevelNodes) // there I got null [] (this.rootLevelNodes) in function but I dont know why I got null result but there where also I want In array format result how it is possible see my below code and help me ?

@Injectable()
export class DynamicDatabase {

  rootLevelNodes: string[] = [];
  constructor(private route : ActivatedRoute, private userService : UserService){}
  upperFolderId;
  urlOfFolder;

  initialData(): DynamicFlatNode[] {

    this.route.params.subscribe(params => {

      this.upperFolderId = params['userid'];
      this.urlOfFolder = params['url']+'/'+this.upperFolderId;

      this.userService.getPatternMainFolder({'urlOfFolder' : this.urlOfFolder}).subscribe(
        (data) => {
          if(data != undefined && data != '' && data.payload != undefined && data.payload != ''){
            for(var i = 0 ; i < data.payload.length ; i++){
              this.rootLevelNodes = data.payload[i].folderName;
              console.log(this.rootLevelNodes); // folder-1
                                                   folder-2
                                                   folder-3
                                                   folder-4
                                                   <-- this type result I got

              // I want this type result 
              console.log(this.rootLevelNodes); // ['folder-1','folder-2','folder-3','folder-4']
            }
          }
        }
      )
    });

    console.log(this.rootLevelNodes);  // [] --> Here I result got null array

     // Here also I want this type result want
    console.log(this.rootLevelNodes); //  ['folder-1','folder-2','folder-3','folder-4']
    return this.rootLevelNodes.map(name => new DynamicFlatNode(name, 0, true));
  }
Dharmesh
  • 5,383
  • 17
  • 46
  • 62

2 Answers2

1

I would split the single function into two parts:

initialData() {
    this.route.params.subscribe(params => {
      this.upperFolderId = params['userid'];
      this.urlOfFolder = params['url']+'/'+this.upperFolderId;
      this.anotherFunction(this.urlOfFolder);
    });
  }

anotherFunction(data) {
    this.userService.getPatternMainFolder({'urlOfFolder' : data}).subscribe(
    (data) => {
     if(data != undefined && data != '' && data.payload != undefined && data.payload != ''){
    for(var i = 0 ; i < data.payload.length ; i++){
      this.rootLevelNodes.push(data.payload[i].folderName);
      console.log(this.rootLevelNodes);
    }
  }
  return this.rootLevelNodes;
  }
 )
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
1

Instead of this.rootLevelNodes = data.payload[i].folderName; do this.rootLevelNodes.push(data.payload[i].folderName);

Parshwa Shah
  • 331
  • 4
  • 14