依赖注入
依赖注入:
DI,Dependency injection
控制反转:
IOC,Inversion of Control
好处:松耦合
注入器:
constructor(private productService:ProductService){}
提供器:
providers:[PrpductService]
providers:[{provide:ProductService,useClass:ProductService}]
providers:[{provide:ProductService,useFactory:() =>{}}]
项目
1.1创建项目
–> ng new di
1.2生成组件
–> ng g component product1
1.3生成服务
–> ng g service shared/product
2.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Product1Component } from './product1/product1.component';
import {ProductService} from './shared/product.service';
@NgModule({
declarations: [
AppComponent,
Product1Component
],
imports: [
BrowserModule
],
/*使用提供器声明在模块里*/
providers: [ProductService],
bootstrap: [AppComponent]
})
export class AppModule { }
product.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor() { }
getProduct(): Product {
return new Product(0, 'iphobeX', 10000, '最新款苹果手机');
}
}
export class Product {
constructor(
public id: number,
public title: string,
public price: number,
public desc: string
) {
}
}
product1.component.ts
import { Component, OnInit } from '@angular/core';
import {Product, ProductService} from '../shared/product.service';
@Component({
selector: 'app-product1',
templateUrl: './product1.component.html',
styleUrls: ['./product1.component.css']
})
export class Product1Component implements OnInit {
/*接收从服务中获取数据*/
product: Product;
/*依赖注入声明所需服务*/
constructor(private productService: ProductService) { }
ngOnInit() {
this.product = this.productService.getProduct();
}
}
product1.component.html
<div>
<h1>商品详情</h1>
<h2>名称:{{product.title}}</h2>
<h2>价格:{{product.price}}</h2>
<h2>描述:{{product.desc}}</h2>
</div>
app.component.html
<div>
<div>
<h1>基本的依赖注入样例</h1>
</div>
<div>
<app-product1></app-product1>
</div>
</div>