简体   繁体   中英

Angular 6 Promise

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.

My Component file :

 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<string> = []; // 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 & Description. const metaData: MetaData = { author: 'Attinad', keywords: 'template, app', description: 'My description' }; this.setMetaData(metaData, 'Home'); } ngOnInit() { this.route.params.subscribe(params => { this.pageType = params['type'] ? params['type'] : 'home'; // Apply theme. if (this.configurationService.themeConfig && 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(() => { 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) => { 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(() => this.displayRails(this.pageType), 1000); } } 

My Controller File

 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<string> = []; // 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[]) => { // 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) => { 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; }; } 

If your more accustomed to work with Observable than Promise, then try the Observable.fromPromise like this:

let myPromise = getSomePromise();
let myObservable = Observable.fromPromise(myPromise);

From what I see in your example, your return statement is misplaced. You do not even need any Promise and should do something like below.

In your controller file :

getRailController(pageType): Observable<RailDataAll[]> {

            return this.homeService.getRails(pageType).pipe(mergeMap((data: CarouselData[]) => {

                // 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) => {
                    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 of(this.homeData);
            });

        }

In your component file :

displayRails(pageType: string): void {

      this.preloaderService.show();

        this.homeController.getRailController(pageType).subscribe(
        data => {
           this.railControlledDatas = data
           console.log('k',this.railControlledDatas);
           this.preloaderService.hide();
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM