[Angular 2] 4. Inject service into component
Angular Service Component INTO Inject
2023-09-14 09:00:55 时间
Before we get too much further, we should mention that putting our model (array) directly in our controller isn't proper form. We should separate the concerns by having another class serve the role of model and inject it into the controller.
Make a FriendsService
class to provide the model with the list of friends.
import {Component, View, bootstrap, NgFor} from 'angular2/angular2'; class FriendsService { names: Array<string>; constructor() { this.names = ["Aarav", "Martin", "Shannon", "Ariana", "Kai"]; } } @Component({ selector: 'display', appInjector: [FriendsService] }) @View({ template: ` <p>My name: {{ myName }}</p> <ul> <li *ng-for="#name of names"> {{ name }} </li> </ul> `, directives: [NgFor] }) class DisplayComponent { myName:string; names: Array<string>; constructor(friendsService: FriendsService) { this.myName = 'Alice'; this.names = friendsService.names; } } bootstrap(DisplayComponent);
相关文章
- angular父子组件传值
- angular框架如何实现父子组件传值、非父子组件传值
- Angular: 最佳实践
- Angular 结合 dygraphs 实现 annotation
- SAP 电商云 Spartacus UI Angular UI 和 Accelerator JSP UI 的混合使用
- angular面试问题_kafka面试题
- Angular 面试题汇总2-Component/Service (Angular v8+)
- uat环境和生产环境的区别_angular 生产环境 相对路径无效
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- Angular 项目中 angular.json builder 字段的可选项介绍
- Angular 框架将进入 2.0 时代
- angular.element方法汇总
- angular简介和其特点介绍