依赖注入
Angular 中的依赖注入(DI)是框架最强大的特性之一。可以将依赖注入视为 Angular 在运行时为你的应用 提供所需资源的能力。依赖项可以是服务或其他资源。
使用服务的一种方式是作为与数据和 API 交互的方式。为了使服务可重用,应该将逻辑保留在服务中,并在需要时在整个应用程序中共享它。
创建服务
创建服务,需要使用 Angular CLI 命令 ng generate service。
- 文件里面必须引入 Injectable,配置装饰器
 
import { Injectable } from "@angular/core";
@Injectable({
  providedIn: "root",
})
export class CarServiceService {
  cars = ["Sunflower GT", "Flexus Sport", "Sprout Mach One"];
  getCars() {
    return this.cars;
  }
  getCar(id: number) {
    return this.cars[id];
  }
}
 
- 需要使用这个服务的组件中
 
import { Component, inject } from "@angular/core";
import { CarServiceService } from "../../services/car-service.service";
@Component({
  selector: "app-about", //这个名字是我们在被的组件中使用的时候,需要写这个名字作为组件名
  standalone: true,
  imports: [FormsModule],
  templateUrl: "./about.component.html",
  styleUrl: "./about.component.css",
})
export class AboutComponent {
  carServices = inject(CarServiceService);
  display = "";
  constructor() {
    this.display = this.carServices.getCars().join(" ❤ ");
  }
}
 

 这样我们就实现了ng中的依赖注入
作为构造函数注入
这里有点类似于java中的@Autowired,思想差不多,感觉
export class AboutComponent {
  // carServices = inject(CarServiceService);
  username = "";
  display = "";
  constructor(private carServices: CarServiceService) {
    this.display = this.carServices.getCars().join(" ❤❤ ");
  }
}
 




















