【发布时间】:2020-05-25 07:12:48
【问题描述】:
我正在学习 Udemy 的 Angular 课程,老师说我们需要在 @Component 注释的提供程序部分指定我们要导入的服务,以告诉 Angular 需要在该组件中注入哪些服务。但是我的组件在没有指定的情况下可以正常工作。
这是为什么呢?
这是我的组件
import { Component, EventEmitter, Input, Output } from '@angular/core';
import {AccountService} from "../services/account-service";
@Component({
selector: 'app-account',
templateUrl: './account.component.html',
styleUrls: ['./account.component.css']
})
export class AccountComponent {
@Input() account: {name: string, status: string};
@Input() id: number;
constructor(private accountService:AccountService) {
}
onSetTo(status: string) {
this.accountService.updateStatus(this.id,status);
}
}
这就是服务
import { Injectable } from '@angular/core';
import {LoggingService} from "./logging.service";
@Injectable({
providedIn: 'root'
})
export class AccountService {
accounts = [
{
name: 'Master Account',
status: 'active'
},
{
name: 'Testaccount',
status: 'inactive'
},
{
name: 'Hidden Account',
status: 'unknown'
}
];
constructor(private loggingService: LoggingService) { }
addAccount(name:string, status:string){
this.accounts.push({name:name, status:status})
this.loggingService.logStatusChanged(status)
}
updateStatus(id:number,status:string){
this.accounts[id].status = status;
this.loggingService.logStatusChanged(status)
}
}
【问题讨论】:
-
如果服务包含在
AppModule中或像您的示例一样使用providedIn: 'root',那么它就是singleton service。在整个应用程序中只有一个实例,并且对所有组件都可用。