gpt4 book ai didi

angular - 为什么我的 Angular 服务无需在 @Component 注释的提供者参数中指定即可工作?

转载 作者:行者123 更新时间:2023-12-03 08:44:29 25 4
gpt4 key购买 nike

我正在学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com