【问题标题】:Angular 6 PromiseAngular 6 承诺
【发布时间】:2018-10-29 21:26:38
【问题描述】:

我试图在组件文件中调用文件控制器,控制器返回一个在文件中可用但在调用者函数中未定义的值,这是一个 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;

        };

    }

【问题讨论】:

  • 看起来你的 displayRails 有一个错误的返回(为什么你会在新的 Promise 执行器函数中返回 Promise)和一个从未解决或拒绝的 Promise(你认为 Promise 构造函数的那些参数是什么?是为了?)
  • 这是我第一次尝试 Promise,我通常会选择 Observables。
  • 你能编辑答案吗
  • 不,无法开始想象您的代码应该如何处理该承诺......它什么时候会解决或拒绝?为什么要返回任何值,因为调用代码完全忽略了它?
  • 其实你看到的函数并没有等待 API 响应,因此它使用空数据执行。

标签: javascript angular promise angular6


【解决方案1】:

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

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

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

在您的控制器文件中:

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

【讨论】:

  • 我在这个实现中遇到了一些错误@rguerin
  • src/app/home/home-controller.ts(39,52) 中的错误:错误 TS2339:“Observable”类型上不存在属性“flatMap”。 src/app/home/home-controller.ts(57,13):错误 TS2322:类型“RailDataAll[]”不可分配给类型“Observable”。 “RailDataAll[]”类型中缺少属性“_isScalar”。 src/app/home/home-controller.ts(60,31):错误 TS2339:“typeof Observable”类型上不存在属性“of”。
  • 您使用的是哪个版本的 RxJs 和 typescript?您是否很好地导入了 Observabe 库 (import { Observable } from 'rxjs';)?
  • rxjs 6 ts 2.9 ,是的,我做到了
  • 你也有 RxJs 兼容包吗?试试“npm i rxjs-compat --save”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
相关资源
最近更新 更多