使用 TypeScript 开发 Angular 应用
1. 依赖注入与 ProductService
依赖注入(DI)在 Angular 开发中扮演着重要角色,它能提高组件的可复用性并减少组件与服务之间的紧密耦合。例如,我们可以通过配置让 Angular 实例化 AnotherProductService 来替代 ProductService ,而使用 ProductService 的 ProductComponent 代码无需修改。
以下是 ProductService 的代码示例:
import { Injectable } from '@angular/core';
import { Product } from './product';
@Injectable({
providedIn: 'root'
})
export class ProductService {
getProduct(): Product {
return {
id: 0,
title: "iPhone XI",
price: 1049.99,
description: "The latest iPhone"
};
}
}
export interface Product {
id: number,
title: string,
price: number,
description:
超级会员免费看
订阅专栏 解锁全文
1536

被折叠的 条评论
为什么被折叠?



