使用 TypeScript 开发 Angular 应用
1. 依赖注入与 ProductService
依赖注入(DI)在 Angular 应用中能提高组件的可复用性并减少耦合。例如,我们可以将 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: string
}
这里将 Product 类型声明为接口,这样在 getProduct() 方法中可以进行类型检查,并且在编译后的 JavaScript 中
超级会员免费看
订阅专栏 解锁全文
1547

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



