Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing server parameters to ngModule after RC5 upgrade

Tags:

angular

I'm trying again to pass parameters to my application. Since RC5, I have to use ngModule. (this solution: Passing asp.net server parameters to Angular 2 app no longer works since RC5)

How to pass parameters to ngModule?

Here's a plunker to illustrate problem: Plunker

index.html:

<script>
  System.import('app').then(module =>   module.main('This is RIGHT'),
                console.error.bind(console)
            );
</script>

main.ts:

import { browserDynamicPlatform } from '@angular/platform-browser-dynamic';
import { provide } from '@angular/core';
import { AppModule } from './app.module';

export function main(test: string) {

  browserDynamicPlatform().bootstrapModule(AppModule, [{ providers: provide('Test', { useValue: test, }) }]);
}

app.module.ts

import { NgModule, provide }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { AppComponent }       from './app.component';

@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    provide('Test', { useValue: 'This is WRONG' })
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}
like image 366
vidalsasoon Avatar asked Aug 15 '16 02:08

vidalsasoon


1 Answers

Update 2

Webpack implementation you can find here Passing server parameters to ngModule with Angular 2 and webpack


Systemjs

Update 1:

We can pass data in the extraProviders property of browserDynamicPlatform function:

main.ts

export function main(test: string) {
  browserDynamicPlatform([{provide: 'Test', useValue: test }])
    .bootstrapModule(AppModule);
}

This way the createAppModule function in app.module.ts is redundant.

Plunker 2.0 Final


Previous version

For RC.5 you can add a method (i.e. createAppModule) in app.module.ts like this:

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

export function createAppModule(test) {
  @NgModule({
    imports: [BrowserModule],
    providers: [
      { provide: 'Test', useValue: test },
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
  })
  class AppModule { }

  return AppModule;
}

This way your main module would be like this:

main.ts

import { browserDynamicPlatform } from '@angular/platform-browser-dynamic';

import { createAppModule } from './app.module';

export function main(test: string) {
  browserDynamicPlatform().bootstrapModule(createAppModule(test));
}

And your starting point remains the same:

index.html

<script>
  System.import('app')
    .then(module => module.main('This is RIGHT'),
       console.error.bind(console)
    );
</script>

Here is Plunker Example

like image 157
yurzui Avatar answered Oct 25 '22 01:10

yurzui