如何将参数传递给Ionic2/Angular2中的提供者构造函数?

And*_*ann 10 dependency-injection typescript ionic2 angular

我试图将我的Ionic2.beta11应用程序移植到新的Ionic2.rc0版本.大多数事情都非常简单,但我对AoT编译器有疑问.

我有一个AuthService:

@Injectable()
export class AuthService {
  constructor(@Inject(Http) http: Http) {
    this.http = http;
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

我将它注入我的src/app/app.module.ts文件中的应用程序:

@NgModule({
  declarations: [
    MyApp,
    ...
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ...
  ],
  providers: [
    AuthService
  ]
})
Run Code Online (Sandbox Code Playgroud)

运行离子服务时一切正常,但是当我尝试构建它时,我收到以下错误:

ngc error: Error: Error at .../.tmp/app/app.module.ngfactory.ts:397:78: Supplied parameters do not match any signature of call target.
Run Code Online (Sandbox Code Playgroud)

396 - 399行:

get _AuthService_74():import44.AuthService {
  if ((this.__AuthService_74 == (null as any))) { (this.__AuthService_74 = new import44.AuthService()); }
  return this.__AuthService_74;
}
Run Code Online (Sandbox Code Playgroud)

问题是new import44.AuthService()需要一个http类型的参数.

有趣的是,一切工作正常,当我手动替换constructor(http: Http)constructor()在定义文件.

我阅读了所有可以找到的StackOverflow答案,但没有一个解决方案解决了我的问题.

我是否需要更改AuthService中的构造函数或将其注入我的应用程序的方式?谢谢您的帮助.

Mar*_*ner 10

您必须改变方式,如何定义提供者:

@NgModule({
  ...
  providers: [
    Http,
    {
      provide: AuthService,
      useFactory: getAuthService,
      deps: [Http]
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

最后一块是工厂功能:

export function getAuthService(http: Http): LoggingService {
  return new AuthService(http);
}
Run Code Online (Sandbox Code Playgroud)

另请参见迁移到Ionic 2 RC 0 - ngc失败


ran*_*al9 0

HttpModule从您的应用程序模块中导入@angular/http,如下所示:

import { HttpModule } from '@angular/http';
@NgModule({
  declarations: [
    MyApp,
    ...
  ],
  imports: [
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ...
  ],
  providers: [
    AuthService
  ]
})
Run Code Online (Sandbox Code Playgroud)

按如下方式更改您的服务并检查一次:

import { Http } from '@angular/http';
@Injectable()
export class AuthService {
  constructor(private http: Http) {
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)