Angular 4:在NgModule提供程序数组中动态添加提供程序

时间:2017-11-10 12:06:47

标签: angular angular2-routing angular-cli

应用程序背景:我的应用程序是使用ASP.net MVC(.net framework 4.6)和几个Angular 4 mini SPA构建的

SPA之一使用this方法来引导组件。简而言之,这个SPA可以引导由一个Angular应用程序管理的多个组件。

问题我想在html视图中存在某个组件时,在providers数组中添加一个提供程序(动态,如果这是正确的单词)。希望你们能帮忙吗?

示例我希望在视图中加载/显示{ provide: APP_BASE_HREF, useValue: '/shoppingbasket/my' }时在提供者数组中添加AddProductToShoppingBasketComponent

代码

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ComponentFactoryResolver, ApplicationRef, Type } from '@angular/core';
import { HTTP_INTERCEPTORS } from "@angular/common/http";
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
//import { APP_BASE_HREF } from "@angular/common";

import { ToastrModule } from "ngx-toastr";
import { NgProgressModule, NgProgressInterceptor } from 'ngx-progressbar';

import { ShoppingModule } from './shopping/shopping.module';
import { SharedModule } from './shared/shared.module';
import { CheckoutModule } from './checkout/checkout.module';

import { AppRoutingModule } from './app-routing.module';


import { AppComponent } from './app.component';
import { ShoppingBasketComponent } from "./shopping/shopping-basket.component";
import { AddProductToShoppingBasketComponent } from './shopping/add-product-to-shopping-basket.component';

const components = [AppComponent, AddProductToShoppingBasketComponent, ShoppingBasketComponent];

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        SharedModule,
        CheckoutModule,
        AppRoutingModule,
        BrowserModule,
        ShoppingModule,
        NgProgressModule,
        BrowserAnimationsModule,
        ToastrModule.forRoot({
            timeOut: 5000,
            positionClass: 'toast-bottom-right',
            preventDuplicates: true,
            closeButton: true
        })
    ],
    providers: [
        //{ provide: APP_BASE_HREF, useValue: '/shoppingbasket/my' },
        { provide: HTTP_INTERCEPTORS, useClass: NgProgressInterceptor, multi: true }
    ],
    entryComponents: components
})
export class AppModule {
    //Reference: https://blog.novatec-gmbh.de/angular-2-in-a-multi-page-application/
    constructor(private resolver: ComponentFactoryResolver) { }
    ngDoBootstrap(appRef: ApplicationRef) {
        components.forEach((componentDef: Type<{}>) => {
            const factory = this.resolver.resolveComponentFactory(componentDef);
            if (document.querySelector(factory.selector)) {
                appRef.bootstrap(factory);
            }
        });
    }
}

0 个答案:

没有答案