title: Angular 6 Promise
body: <p>I am trying to call a file controller inside the component file, the controller returns a value which is avaliable inside the file but is undefined in the caller function, which is a JS threading issue, so I am trying to solve it via promise but I am new with Promise and its not going well, Please go through two files and tell me where I went wrong.</p>
  
  <p>My Component file :
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, OnInit, OnDestroy } from '@angular/core';
  import { Meta, Title } from '@angular/platform-browser';
  import { ActivatedRoute } from '@angular/router';
  import { BaseComponent } from '../core/base.component';
  import { MetaData } from '../core/interfaces/Meta';
  import { HomeService } from './home.service';
  import { CarouselOptions, CarouselData } from '../shared/components/carousel/interface/Carousel';
  import { Subscription } from 'rxjs';
  import { Utility } from '../core/utility';
  import { ConfigurationService } from '../configuration/configuration.service';
  import { PreloaderService } from '../shared/components/preloader/preloader.service';
  import { InfiniteScrollModule } from 'ngx-infinite-scroll';
  import { HomeController } from './home-controller';
  
  @Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
  })
  export class HomeComponent extends BaseComponent implements OnInit, OnDestroy {
  
    railsData: CarouselData[]; // Rails data.
    railOptions: CarouselOptions; // Rails options.
    railIds: Array&lt;string&gt; = []; // Rail Ids.
    railsSubscription: Subscription;
    pageType: string;
    backgroundColor: string; // Page background color.
    backgroundImage: string;
    railServiceData;
    railInfo;
    railControlledDatas;
  
  
  
    constructor(meta: Meta, title: Title, private route: ActivatedRoute, public homeService: HomeService
      , public utility: Utility, public configurationService: ConfigurationService,
      private preloaderService: PreloaderService, private InfiniteScrollModule: InfiniteScrollModule,
      private homeController: HomeController) {
      super(meta, title); // Call base component
  
      // Initialise the variables.
      this.railsData = [];
      this.railOptions = {};
      this.pageType = 'home';
      // Set the Title &amp; Description.
      const metaData: MetaData = { author: 'Attinad', keywords: 'template, app', description: 'My description' };
      this.setMetaData(metaData, 'Home');
    }
  
    ngOnInit() {
      this.route.params.subscribe(params =&gt; {
        this.pageType = params['type'] ? params['type'] : 'home';
  
        // Apply theme.
        if (this.configurationService.themeConfig &amp;&amp; this.configurationService.themeConfig.theme_json) {
          const homeTheme = JSON.parse(this.configurationService.themeConfig.theme_json).landingPage;
  
          this.backgroundColor = homeTheme.bgColor ? homeTheme.bgColor : ''; // Background color.
          this.backgroundImage = this.configurationService.getAssetByKey(homeTheme.bgImage) ?
            this.configurationService.getAssetByKey(homeTheme.bgImage) : ''; // Background Image.
        }
        // Scroll to the page top postion.
        this.utility.scrollToTop();
  
        // Fetch and display the rails.
        // setTimeout(() =&gt; {
          this.displayRails(this.pageType);
        // }, 1000);
      });
    }
  
    ngOnDestroy() {
      // Clear the rail count variable in the service.
      this.homeService.clearRails();
  
      // Unsubscribe the observables.
      if (this.railsSubscription) {
        this.railsSubscription.unsubscribe();
      }
    }
  
    /**
     * @description method to display the rails.
     * @returns - Observable SessionResponse
     */
    displayRails(pageType: string): void {
      const promise = new Promise((resolve, reject) =&gt; {
        this.preloaderService.show();
   
          this.railControlledDatas = this.homeController.getRailController(pageType);
          console.log('k',this.railControlledDatas);
       
          this.preloaderService.hide();
        return promise
      }
    }
  
    /**
     * @description sample method for handling lazy loading scroll down event
     * @returns void
     */
    onScrollDown(): void {
      // Call the next set of rails while scrolling.
      // And avoid the error while clicking back button setTimeout added.(Lazy Loading issue)
      setTimeout(() =&gt; this.displayRails(this.pageType), 1000);
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>My Controller File</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import { HomeTransformation } from './home-transformation'
  import { Injectable } from '@angular/core';
  import { RailsData, RailDataAll } from './interfaces/homeTranformation';
  import { CarouselOptions, CarouselData } from '../shared/components/carousel/interface/Carousel';
  import { HomeService } from './home.service';
  import { HomeComponent } from './home.component';
  
  @Injectable()
  export class HomeController {
      railsData: CarouselData[]; // Rails data.
      railOptions: CarouselOptions; // Rails options.
      railIds: Array&lt;string&gt; = []; // Rail Ids.
      homeData: RailDataAll[];
      homeServices;
      railSubscription;
      railInfo;
      railsSubscription;
      constructor(private transformObj: HomeTransformation, private homeService: HomeService) {
          this.railsData = null;
  
      }
      /**
        * @description Accepts data from api and feeds to Transformation
        * @returns homeData
        */
      // servicedata = this.server();
      // transformdsata
      // = this.transformObj(serverifd);return trandda;
      getRailController(pageType): RailDataAll[] {
  
         
              this.railsSubscription = this.homeService.getRails(pageType).subscribe((data: CarouselData[]) =&gt; {
                  // Concat the new and old rail data.
                  data = { ...this.railsData, ...data };
  
                  // Get the keys from the rails object.
                  this.railIds = Object.keys(data);
                  // Append the railoption to every rail.
                  this.railIds.map((railId: string) =&gt; {
                      this.railInfo = this.homeService.getRailInfo(railId); // Get the rail info for corresponding rail id.
                      data[railId].railOptions = this.homeService.getRailOptions(this.railInfo); // Get the rails options.  
                      // console.log(data);
                  });
                  // Assign data to the rails.
                  this.railsData = data;
                  console.log(this.railsData);
                  this.homeData = this.transformObj.transformgetRails(this.railsData);
                  console.log(this.homeData);
              });
  
              return this.homeData;
  
          };
  
      }</code></pre>
  </div>
  </div>
  </p>