作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习 Angular 的 Udemy 类(class),老师说我们需要在 @Component 注释的提供者部分中指定要导入的服务,以告诉 Angular 需要在该组件中注入(inject)哪个服务。但我的组件无需指定即可正常工作。
这是为什么?
这是我的组件
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)
}
}
最佳答案
它的工作是由于 providedIn: 'root' 自 Angular 6 起可用,这告诉 Angular 在应用程序根目录中提供服务,以便在您的组件上可用。如果您要使用的服务特定于组件,那么您可以在组件级别专门提供它。
关于angular - 为什么我的 Angular 服务无需在 @Component 注释的提供者参数中指定即可工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997464/
我是一名优秀的程序员,十分优秀!