typescript函数在另一个类中调用函数时返回undefined

时间:2017-02-16 17:41:09

标签: javascript angular typescript typescript2.0

在我的 Angular 2 项目中,我有这个课程:

export class ApiEnvConf {

    /**
     * @type {Object}
     */
    public _dev: {environnement: string, basePath: URL};

    /**
     * @type {Object}
     */
    public _staging: {environnement: string, basePath: URL};

    /**
     * @type {Object}
     */
    public _prod: {environnement: string, basePath: URL};

    constructor(){
        this._dev;
        this._staging;
        this._prod;
    }

    /**
     * @return {Object}
     */
    get devEnv(): {"environnement": string, "basePath": URL} {
        return this._dev;
    }

    /**
     * @return {Object}
     */
    get stagingEnv(): {"environnement": string, "basePath": URL} {
        return this._staging;
    }

    /**
     * @return {Object} 
     */
    get prodEnv(): {"environnement": string, "basePath": URL} {
        return this._prod;
    }

    /**
     * @param  {string} environnement
     * @param  {URL}    basePath
     * @return {Object}
     */
    set devEnv(newDevEnvArray: {environnement: string, basePath: URL}){
      this._dev = newDevEnvArray;
    }

    /**
     * @param  {string} environnement
     * @param  {URL}    basePath
     * @return {Object}
     */
    set stagingEnv(newStagingEnvArray: {environnement: string, basePath: URL}) {
      this._staging = newStagingEnvArray;
    }

    /**
     * @param  {string} environnement
     * @param  {URL}    basePath
     * @return {Object}
     */
    set prodEnv(newProdEnvArray: {environnement: string, basePath: URL}) {
      this._prod = newProdEnvArray;
    }
}

如您所见,我导出此类以便在其他文件(其他类)中使用它。以下是使用此类的文件的一个示例:

import { Injectable, Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { ApiEnvConf } from './api-env-conf-class';

@Injectable()
@Component({
  providers: [ ApiEnvConf ]
})
export class ImportConfig {

  /**
   * @type {ApiEnvConf}
   */
  public envParam = new ApiEnvConf();

  constructor(
    public http: Http
  ) {}

  loadEnvData() {
    this.http.get('assets/env-config/parameters.json')
    .map((res: Response) => (res.json()))
    .subscribe(
      data => {
        this.envParam  = this.instanciateApiEnvConfClass(data);
        return this.envParam;
      },
      err => {
          console.log("oops !");
          return err;
      }
    )
  }

  instanciateApiEnvConfClass(data: Object){
    let apiEnvConf = new ApiEnvConf();
    // set dev by calling getter of ApiEnvConf class
    apiEnvConf.devEnv = {
      environnement: data["dev"]["environnement"],
      basePath: new URL(data["dev"]["basePath"])
    };
    // set stagging by calling getter of ApiEnvConf class
    apiEnvConf.stagingEnv = {
      environnement: data["staging"]["environnement"],
      basePath: new URL(data["staging"]["basePath"])
    };
    // set prod by calling getter of ApiEnvConf class
    apiEnvConf.prodEnv = {
      environnement: data["prod"]["environnement"],
      basePath: new URL(data["prod"]["basePath"])
    };
    return apiEnvConf;
  }
}

因此,如果您查看loadEnvData()函数,如果我在console.log(this.envParam); 语句之前生成return ,我会在控制台浏览器中显示此结果:< / p>

enter image description here

所以我的班级ApiEnvConf不是空的,并且拥有我需要的所有属性。

类ImportConfig是我在许多文件中使用的另一个类,用于初始化环境配置。

所以在另一个文件夹的另一个类中我有这个类:

import { Injectable, Component } from '@angular/core';
import { ImportConfig } from '../services/import-config';
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [ ImportConfig ]
})
export class Test {
constructor(public http: Http, public config: ImportConfig) {
    this.config;
    this.check();
  }

  check() {
    let test = this.config.loadEnvData();
    console.log(test);
  }

  /*
    ...
    ...
    ...
  */
}

console.log(test);的输出会返回“undefined”。我哪里错了?

1 个答案:

答案 0 :(得分:3)

你已经调用了一个不会返回任何东西的异步函数:

  loadEnvData(env: string = "dev") {
    this.http.get('assets/env-config/parameters.json')
    .map((res: Response) => (res.json()))
    .subscribe(
      data => {
        this.envParam  = this.instanciateApiEnvConfClass(data);
        return this.envParam;
      },
      err => {
          console.log("oops !");
          return err;
      }
    )
    // Note: *here* is where you would, in theory, return something
  }

当您调用没有明确return的函数时,它会返回undefined。您已假设此功能是同步的,它不是。

您的loadEnvData函数应提供一些回调机制来指示完成;在那里你可以访问加载的数据。