angular - 可注入(inject)服务中的引导组件

标签 angular asp.net-core angular2-services

在我们的 ASP.NET Core 应用程序中,我们使用 Ajax 动态加载一些 HTML 部分 View ,以不刷新页面。在这些 View 中,我们添加 Angular 2 组件,因此当我们显示部分 View 时,我们需要引导该组件:这就是我们在可注入(inject)服务中所做的事情。

部分 View :

<home></home>

服务:

@Injectable()
export class ComponentService {
    constructor() { }

    loadComponent(path: string): void {
        System
            .config({
                packages: {
                    app: {
                        defaultExtension: 'js',
                    }
                }
        });

        System
            .import('app/home/home.component')
            .then((component) => {
                console.log("Import done !");
            })
            .catch((error) => {
                console.error.bind(console);
            });
    }
}

注意:直接插入部分 View 中的完全相同的代码第一次可以工作,之后出现错误:“angular2.dev.js:23941 异常:预计不在 Angular Zone 中,但它确实在! ”。

我在控制台中看到(在我的服务中)没有错误,因为我看到“导入完成!”并且 component 对象已加载,但未引导。

组件:

@Component({
    selector: 'home',
    templateUrl: 'home.component.html'
})
export class Home {
    // Some logic    
}

bootstrap(Home,
    [
        HTTP_PROVIDERS,
        HomeService
    ]);

有什么想法吗?这背后的重要思想是:如何多次加载一个 Angular 2 组件?

最佳答案

事实上,您可以多次引导,但不能引导同一个组件。这是 Angular2 的限制

也就是说,我也会定义一次 SystemJS 的配置。

我不知道您的实际用例是什么,Angular2 提供了一种使用 DynamicComponentLoader 动态加载其他组件(例如引导组件)内的组件的方法。

请参阅此链接了解更多详细信息:

关于angular - 可注入(inject)服务中的引导组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837585/

相关文章:

angular - 在 ngClass 的条件实现中使用变量

html - 如何使用 Ionic 实现捏合/捏合?

c# - 从 API 获取数字并将其放入变量中

Angular:使用服务延迟加载模块

typescript - Angular2 - 使用服务在组件之间共享数据

angular - Angular 4.3 中的单元测试 HttpClientModule : undefined return value from HttpTestingController. expectOne(url)

asp.net - IApplicationBuilder 存在于 Microsoft.AspNet.Http.Abstractions 和 Microsoft.AspNet.Http 中

entity-framework - 在 ASP.NET Core 中响应后做一些工作

Angular 2 RC 5 Bootstrap 自定义 HTTP 类 TypeError : Cannot read property 'toString' of null

angular - 无法从 well-known/openid-configuration 获取配置