Angular 6 Promise - PullRequest
       7

Angular 6 Promise

0 голосов
/ 29 октября 2018

Я пытаюсь вызвать файловый контроллер внутри файла компонента, контроллер возвращает значение, которое доступно внутри файла, но не определено в функции вызывающей стороны, которая является проблемой потоков JS, поэтому я пытаюсь решить ее с помощью обещаю, но я новичок в Promise, и с ним не все в порядке. Пожалуйста, просмотрите два файла и скажите, где я ошибся.

Файл моего компонента:

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

Мой файл контроллера

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;

        };

    }

1 Ответ

0 голосов
/ 29 октября 2018

Если вы привыкли работать с Observable, а не с Promise, попробуйте Observable.fromPromise следующим образом:

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

Из того, что я вижу в вашем примере, ваше выражение return неуместно. Вам даже не нужно обещание, и вы должны сделать что-то вроде ниже.

В вашем файле контроллера:

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

        }

В вашем файле компонента:

displayRails(pageType: string): void {

      this.preloaderService.show();

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