【发布时间】:2018-01-14 21:23:27
【问题描述】:
我是 Angular 2 的新手,我有以下关于 服务 的问题。
进入主视图(与app.component.ts类相关的那个)我有这种情况:
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-8 col-md-offset-2">
<app-new-account (accountAdded)="onAccountAdded($event)"></app-new-account>
<hr>
<app-account
*ngFor="let acc of accounts; let i = index"
[account]="acc"
[id]="i"
(statusChanged)="onStatusChanged($event)"></app-account>
</div>
</div>
</div>
因此,在这个视图中,我有 2 个子组件(app-new-account 和 app-account)。
进入我拥有的主要 AppComponent 组件类:
import {Component, OnInit} from '@angular/core';
import {AccountsService} from './accounts.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AccountsService]
})
export class AppComponent implements OnInit {
accounts: {name: string, status: string}[] = [];
// Injectiong the AccountsService:
constructor(private accountsService: AccountsService) {}
ngOnInit() {
this.accounts = this.accountsService.accounts;
}
}
我通过这一行将 AccountsService 定义为组件装饰器中的服务:
providers: [AccountsService]
据我了解,该类是 AccountsService 必须注册为 AppComponent 主组件和 其所有子组件的服务强>。这个断言是真的还是我遗漏了什么?
也就是说,与前面的app-new-account和app-account标签相关的两个子组件类共享同一个实例AccountsService 类即服务?
这是因为在这 2 个子组件的 providers 数组中我没有 AccountsService 吗?
这是我的推理正确还是我遗漏了什么?
【问题讨论】:
标签: javascript angular angular2-services javascript-framework