美文网首页
8、angular学习第七天(依赖注入的基础使用)

8、angular学习第七天(依赖注入的基础使用)

作者: LH_0811 | 来源:发表于2018-10-08 10:53 被阅读32次

在一个组件中 分为 mvc结构
m(model)--就是model 就是组件中可能使用到的实体类。
v(view)--就是component中的html。
c(controller)--就是ts文件中的数据处理。

在编写过程中,可能存在很多相同的数据处理方式。
比如:
可能很多component里面的console.log都需要格式化输出。
可能很多component里面的都要获取产品的详情。
这时候可以把这些通用的方法放到一个service中。并将service注入到c中,这样,就可以减少重复代码,提高代码的可维护性。

angular中生成一个service可以使用angular-cli命令

ng g service   (share/) xxxx

(share/)的意思是把service生成的路径放到share文件夹下面 可以让路径更加清晰
使用
ng g service share/product
会自动生成service所需的两个文件

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor() { }

  getProduct(): Product{
    return new Product(0,"iphone7",5899,"iphone7desc")
  }
}


export class  Product {
  constructor(
    public id: number,
    public title: string,
    public price: number,
    public desc: string
  ){

  }



}

编写号servie中的代码后把service放到模块的提供器中。

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 "./shard/product.service";
import { Product2Component } from './product2/product2.component';

@NgModule({
  declarations: [
    AppComponent,
    Product1Component,
    Product2Component
  ],
  imports: [
    BrowserModule
  ],
  providers: [ProductService],
  bootstrap: [AppComponent]
})
export class AppModule { }

这样就可以在模块的所有的component里面使用找个service了

import { Component, OnInit } from '@angular/core';
import {Product, ProductService} from "../shard/product.service";

@Component({
  selector: 'app-product1',
  templateUrl: './product1.component.html',
  styleUrls: ['./product1.component.css']
})
export class Product1Component implements OnInit {

  product: Product;

  constructor(private prouductService:ProductService) { }

  ngOnInit() {

    this.product = this.prouductService.getProduct();

  }

}

ProductService使用了@Injectable声明。所以可以直接在需要他的类的构造方法中注入使用。

相关文章

网友评论

      本文标题:8、angular学习第七天(依赖注入的基础使用)

      本文链接:https://www.haomeiwen.com/subject/seudaftx.html