提供器一

    科技2023-12-13  96

    1.product.service.ts

    import { Injectable } from '@angular/core'; import {LoggerService} from './logger.service'; @Injectable({ providedIn: 'root' }) export class ProductService { constructor(private logger: LoggerService) { } // tslint:disable-next-line:typedef getProduct(): Product { this.logger.log('log方法被调用'); return new Product(0, 'Iphone10', 8777, '价格真贵!'); } } export class Product{ constructor( public id: number, public title: string, public price: number, public desc: string ) { } }

    2.another-product.service.ts

    import { Injectable } from '@angular/core'; import {Product, ProductService} from './product.service'; import {LoggerService} from './logger.service'; @Injectable({ providedIn: 'root' }) export class AnotherProductService implements ProductService{ constructor(public logger: LoggerService) { } getProduct(): Product { return new Product(1, 'Iphone10 plus', 12777, '价格上天了!'); } }

    3.logger.service.ts

    import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LoggerService { constructor() { } // tslint:disable-next-line:typedef log(message: string){ console.log(message); } }

    4.app.module.ts

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

    5.product1.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 { public product: Product; constructor( private productServe: ProductService ) { } ngOnInit(): void { this.product = this.productServe.getProduct(); } }

    6.product2.ts

    import { Component, OnInit } from '@angular/core'; import {Product, ProductService} from '../shared/product.service'; import {AnotherProductService} from '../shared/another-product.service'; @Component({ selector: 'app-product2', templateUrl: './product2.component.html', styleUrls: ['./product2.component.css'], providers: [{ provide: ProductService, useClass: AnotherProductService }] }) export class Product2Component implements OnInit { public product: Product; constructor( private productSerive: ProductService ) { } ngOnInit(): void { this.product = this.productSerive.getProduct(); } }

    7.product1  product2 HTML

    <div> <h1>商品名称{{product.title}}</h1> <h1>商品价格{{product.price}}</h1> <h1>商品描述{{product.desc}}</h1> </div>

     

    Processed: 0.027, SQL: 8