《angular 高级编程》学习集锦

# 第 2 章 第一个 Angular 程序

添加第三方库(全局范围)

npm install bootstrap

在 angular.json 配置文件中,把关联的脚本文件添加到 "scripts" 数组中:

最后再运行或重启 ng serve,看看你的应用是否正在使用 Bootstrap 4。

参考:https://angular.cn/guide/using-libraries

第 7 章 SportsStore: 一个真实的应用程序

一个有用的npm包,json-server

下面是 angular 的结构

│ favicon.ico
│ index.html                       <app-root>
│ main.ts                            检查引导文件(项目更改,编译并重新加载浏览器)
│ styles.css

├─app
│ │ app.component.css
│ │ app.component.html
│ │ app.component.ts     根组件 AppComponent
│ │ app.module.ts            根模块 @NgModule
│ │
│ ├─admin                         管理功能
│ ├─model                         数据模型
│ │ model.module.ts            providers: [ProductRepository, StaticDataSource]
│ │ product.model.ts            类 Product
│ │ product.repository.ts     类 ProductRepository
│ │ static.model.ts                类 StaticDataSource
│ │
│ └─store                           购物功能
│ store.component.css
│ store.component.html
│ store.component.spec.ts
│ store.component.ts
│ store.module.ts

全局注入@Injectable

看看ProductRepository的注入方式 @Injectable

@Injectable()
export class ProductRepository {...}

因为 StoreComponent 构造函数注入了 ProductRepository

export class StoreComponent implements OnInit {

  constructor(private repostory:ProductRepository) { }

这里报错了。

在应用程序根级别,允许将其注入应用程序中的其他类。这可以通过将 providedIn: 'root' 字段添加到 @Injectable 装饰器来实现

解决办法:

  • Make sure ProductRepository is exported so it can be injected elsewhere:
@Injectable({  providedIn: 'root'
})
export class ProductRepository {
  //...
}
posted @ 2023-08-14 22:43  【唐】三三  阅读(24)  评论(0编辑  收藏  举报