制作 AoT 兼容的 DI

Making AoT compatible DI

我有一个使用 angular rc4 的工作项目,它在更新到 angular 2.0.0

后出现故障

我遇到以下错误:

Error encountered resolving symbol values statically. Calling function 'createStore', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol appStore

此代码不再有效:

//Redux - ReduxThunk - rootReducer
import { Store, createStore, applyMiddleware } from 'redux';
import ReduxThunk  from 'redux-thunk';
import { rootReducer } from '../modules/rootReducer';

const appStore = createStore(
  rootReducer,
  applyMiddleware(ReduxThunk)
)

@NgModule({
...
  providers: [
    { provide: 'AppStore', useValue: appStore }
  ]
})

解决这个问题的最佳方法是什么?

这是我在 app.ts 中使用 angular rc4

的根组件文件
import { Component, provide } from '@angular/core';
import { Platform, ionicBootstrap } from 'ionic-angular';
import { StatusBar } from 'ionic-native';

//For Navigation
import { TabsPage } from './pages/tabs/tabs';

//Redux
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk  from 'redux-thunk';
import rootReducer from './modules/rootReducer';

const appStore = createStore(
  rootReducer,
  applyMiddleware(ReduxThunk)
);

@Component({
  template: `<ion-nav [root]="tabsPage"></ion-nav>`
})

export class MyApp {

    private tabsPage: any;

    constructor(
        private platform:Platform, 
        @Inject('AppStore') private appStore: any
        ) {
        });

        this.tabsPage = TabsPage;

        platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            StatusBar.styleDefault();
        });
    }   
}

ionicBootstrap(MyApp, [
    provide('AppStore', { useValue: appStore })
])

如果在 createStore 函数中的任何地方使用了 unnamed/unexported 函数,您将得到同样的错误 - 很可能就是这种情况。我想你有两个选择:

1。尝试修改您的代码,希望问题出在您的代码中。

我会像@estus 推荐的那样尝试useFactory,但你必须使用命名函数,而不是匿名函数。而且必须是函数引用,而不是指向函数的const。

export function appStore() {
  return createStore(
    rootReducer,
    applyMiddleware(ReduxThunk)
  );
}

@NgModule({
...
  providers: [
    { provide: 'AppStore', useFactory: appStore }
  ]
})

2。尝试使用更 angular 2 友好的 redux 实现

我正在使用 ngrx and it works well. ng2-redux 是另一种选择,但我还没有尝试过。