How to pass parameters rendered from backend to angular2 bootstrap method

前端 未结 4 550
感动是毒
感动是毒 2020-11-21 23:58

Is there a way to pass arguments rendered on the backend to angular2 bootstrap method? I want to set http header for all requests using BaseRequestOptions with value provide

4条回答
  •  旧巷少年郎
    2020-11-22 00:16

    The only way to do that is to provide these values when defining your providers:

    bootstrap(AppComponent, [
      provide(RequestOptions, { useFactory: () => {
        return new CustomRequestOptions(/* parameters here */);
      });
    ]);
    

    Then you can use these parameters in your CustomRequestOptions class:

    export class AppRequestOptions extends BaseRequestOptions {
      constructor(parameters) {
        this.parameters = parameters;
      }
    }
    

    If you get these parameters from an AJAX request, you need to bootstrap asynchronously this way:

    var appProviders = [ HTTP_PROVIDERS ]
    
    var app = platform(BROWSER_PROVIDERS)
      .application([BROWSER_APP_PROVIDERS, appProviders]);
    
    var http = app.injector.get(Http);
    http.get('http://.../some path').flatMap((parameters) => {
      return app.bootstrap(appComponentType, [
        provide(RequestOptions, { useFactory: () => {
          return new CustomRequestOptions(/* parameters here */);
        }})
      ]);
    }).toPromise();
    

    See this question:

    • angular2 bootstrap with data from ajax call(s)

    Edit

    Since you have your data in the HTML you could use the following.

    You can import a function and call it with parameters.

    Here is a sample of the main module that bootstraps your application:

    import {bootstrap} from '...';
    import {provide} from '...';
    import {AppComponent} from '...';
    
    export function main(params) {
      bootstrap(AppComponent, [
        provide(RequestOptions, { useFactory: () => {
          return new CustomRequestOptions(params);
        });
      ]);
    }
    

    Then you can import it from your HTML main page like this:

    
    

    See this question: Pass Constant Values to Angular from _layout.cshtml.

提交回复
热议问题