【问题标题】:Should I use Angular 2 Components or Services我应该使用 Angular 2 组件还是服务
【发布时间】:2017-05-17 14:11:49
【问题描述】:

我写了一个 angular 2 组件:

@Component({
  templateUrl: ',
  selector: 'dino',
  templateUrl: './dino.component.html',
  styleUrls: ['./dino.component.css']

})
export class DinoComponent {
...
}

它是一个包含在模式窗口中的图像查看器。

我想在我的应用程序的不同部分(如服务)共享此组件。

如果我在应用程序的不同部分使用选择器,它将创建许多 组件占用内存的实例,对吗?

查看器应该只加载一次,并且只有图像应该根据分散在我的应用程序中的按钮可访问的不同 URL 进行更改。

我知道我可以创建一个根据请求加载图像的服务,但是我如何将模态与模板一起用作服务,以便菜单、框架等常见部分只加载一次?服务可以关联一个 html 模板吗?

如何确保模态查看器是整个应用共享的单例?

感谢您的帮助。

【问题讨论】:

    标签: angular angular2-template angular2-services angular2-components


    【解决方案1】:

    为您的组件和服务创建一个模块,如下所示:

    @NgModule({
      imports: [
        CommonModule
      ],
      declarations: [YourComponent],
      exports: [YourComponent]
    })
    export class TranslationModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: YourModule,
          providers: [
            YourService
          ]
        };
      }
    }
    

    在您的app.module 中将模块导入为YourModule.forRoot(),在所有其他模块中将其导入为YourModule。将您的图像保留在服务中。

    这样你的服务就是一个单例。您的组件标签是否被多次使用并不重要。不显示就不会渲染。

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2023-03-11
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 2011-11-12
      • 2018-12-14
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多