javascript - Angular 6 promise

标签 javascript angular promise angular6

我试图在组件文件内调用文件 Controller , Controller 返回一个在文件内可用但在调用者函数中未定义的值,这是一个 JS 线程问题,所以我尝试通过Promise,但我是 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);
  }
}

我的 Controller 文件

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;

        };

    }

最佳答案

如果您更习惯使用 Observable 而不是 Promise,那么请尝试使用 Observable.fromPromise,如下所示:

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

从我在您的示例中看到的情况来看,您的 return 语句放错了位置。您甚至不需要任何 Promise,应该执行如下操作。

在你的 Controller 文件中:

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

关于javascript - Angular 6 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045447/

相关文章:

javascript - 将图像上传到 Canvas 并在新选项卡中显示

javascript - 为什么更喜欢 defaults() 而不是 Javascript 原型(prototype)设计?

angular - 在 Angular Material Design 中输入数字?

asp.net - Visual Studio 2017 Angular 6 显示 "Cannot Get/"仅限首次尝试

javascript - 带循环的 Node promise

javascript - 如何使用 react-google-charts 设置单个点的样式?

Angular 10 : Formatting date in html

javascript - NodeJS Promises 无法编辑现有的 'model'

javascript - 等待多个异步函数的 promise 链相当于什么?

javascript - 使用语句扩展语法 ES6