简化Angular

时间:2017-04-11 18:57:18

标签: angular

在使用Angular 2之前,我能够使用以下内容导入/导出我的组件:

import * as containersComponent from './containers'
import * as uiComponent from './ui'
import * as allDirectives from './directives'

export function mapValuesToArray(obj){ return Object.keys(obj).map(key => obj[key]) }
export const containers = [...mapValuesToArray(containersComponent)]
export const ui = [...mapValuesToArray(uiComponent)]
export const directives = [...mapValuesToArray(allDirectives)]

然后我宣布他们是这样的:

@NgModule({
  declarations: [ AppComponent, containers, ui, directives ],
   ...
})

现在,自从我搬到Angular 4后,我收到了这个错误:

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function 

有人能帮帮我吗?

编辑以满足对andrei-macarie的更多细节的需求

我收到的错误是指对mapValuesToArray(obj)的调用。 Angular 4不接受我称之为这样的函数。 即使我以另一种方式移动函数,例如,如果我直接在const中调用Object.Key(obj)函数,我也会遇到同样的错误。

为了说明,此功能在Angular 2中适用于提供者:

@NgModule({
    ...
    providers:    [
        {
          provide: APP_INITIALIZER,
          useFactory: (config: LanguagesService) => () => config.load(),
          deps: [LanguagesService],
          multi: true
        }]
    ...
})

在Angular 4中,我得到的错误与我在顶部发布的日志相同,但是对于config.load的调用。 为了避免这种情况,我做了这个:

export function languagesLoader(config: LanguagesService) {
  return () => config.load()
}

@NgModule({
  providers:    [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: languagesLoader,
      deps: [LanguagesService],
      multi: true
    }]
    ...
})

我试图解决当前的问题,它不起作用。所以,我的问题是如何调用这样的函数进行声明?但是,也许有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:0)

这个应该作为documentation州:

interface NgModule {
providers : Provider[]
declarations : Array<Type<any>|any[]>
imports : Array<Type<any>|ModuleWithProviders|any[]>
exports : Array<Type<any>|any[]>
entryComponents : Array<Type<any>|any[]>
bootstrap : Array<Type<any>|any[]>
schemas : Array<SchemaMetadata|any[]>
id : string
}

同时查看更改日志时发现什么,但发现它们正在展平code内的数组。

您还可以使用自己的代码自行展平和重复数据删除,看看是否有效:

function flattenArray(tree: any[], out: Array<any> = []): Array<any> {
  if (tree) {
    for (let i = 0; i < tree.length; i++) {
      const item = resolveForwardRef(tree[i]);
      if (Array.isArray(item)) {
        flattenArray(item, out);
      } else {
        out.push(item);
      }
    }
  }
  return out;
}

function dedupeArray(array: any[]): Array<any> {
  if (array) {
    return Array.from(new Set(array));
  }
  return [];
}

function flattenAndDedupeArray(tree: any[]): Array<any> {
  return dedupeArray(flattenArray(tree));
}

所以只需致电flattenAndDedupeArray(yourDeclarations)

注意:您可以mapValuesToArray(obj)

而不是使用Object.values(obj)