如何在Angular2中注入相同组件的新实例 [英] How to inject new instance of same component in Angular2

查看:61
本文介绍了如何在Angular2中注入相同组件的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[UPDATE]请阅读评论历史记录以了解上下文.

全部:

我对angular2还是陌生的,当我遵循它的快速入门指南时,一个问题使我感到困惑:

I am pretty new to angular2, when I follow its quickstart guide, one question confuses me:

我将app.component.ts简化为:

I simplify the app.component.ts as:

import { Component } from "angular2/core";
@Component({
    selector: "my-app",
    template: "<div>{{title}}</div>"
})
export class AppComponent {
        title = "Tour of Heroes" + Math.random();
}

然后我将另一个my-app标签添加到index.html中,例如:

And I add another my-app tag into index.html like:

  <body>
    <my-app>Loading...</my-app>
    <my-app>Loading...</my-app>
  </body>

我想知道为什么第二个无法渲染吗?

与此相关的另一个问题是:

Another question related to this is:

如果我将两个相同组件的实例放置在一起,则每个实例都将保留自己的成员变量,但是如果我将服务注入一个组件,则所有组件实例都共享相同的服务实例,我发现唯一明显的区别是它们使用的是不同的注解(除此之外,它们都导出一个类):@Component和@Injectable,一个在指令数组中,另一个在providers数组中.我想知道这两个注解是否可以告诉角度如何处理实例或指令数组和提供者数组?

If I put two instance of same component, each one will keep their own member variable, but if I inject service into one component, then all component instances share the same service instance, I find the only obvious diff is they use different annotation( other than this, they both export a class): @Component and @Injectable, and one in directives array while the other in providers array. I wonder if these 2 annotation tell angular how can treat the instance or the directives array and providers array do that?

推荐答案

Angular2不允许在HTML页面中两次自举相同的组件.

Angular2 doesn't allow to bootstrap the same component twice in an HTML page.

但是,如果要在同一HTML页面中,则可以引导不同的应用程序组件.

This is however possible to bootstrap different application components if you want in a same HTML page.

有关更多详细信息,请参阅此文档:

See this documentation for more details:

  • https://angular.io/docs/ts/latest/api/platform/browser/bootstrap-function.html (Section "Bootstrapping Multiple Applications")

修改

关于第二个问题,您需要知道 @Component @Injectable 是修饰符.他们负责包装"目标实例,并通过基于构造的元数据在构造函数中提供正确的依赖实例来允许依赖注入.

Regarding your second question, you need to be aware that @Component and @Injectable are decorators. They are responsible to "wrap" target instances and allow dependency injections by providing right dependency instances in constructor based on configured metadata.

关于分层注入器,您可以查看以下链接:

Regarding hierarchical injectors, you could have a look at this link:

这篇关于如何在Angular2中注入相同组件的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆