import { Injectable } from '@angular/core'; import { ProductServiceService, Product } from './product-service.service'; @Injectable() export class AnotherProductServiceService implements ProductServiceService { getProduct(): Product { return new Product(2, "sunsung7"); } constructor() { } }
import { Component, OnInit } from '@angular/core'; import { Product, ProductServiceService } from '../shared/product-service.service'; import { AnotherProductServiceService } from '../shared/another-product-service.service'; @Component({ selector: 'app-product2', templateUrl: './product2.component.html', styleUrls: ['./product2.component.css'], providers: [{ provide:ProductServiceService,useClass:AnotherProductServiceService }] }) export class Product2Component implements OnInit { product: Product; constructor(private productService: ProductServiceService) { } ngOnInit() { this.product = this.productService.getProduct(); } }
<p> 商品Id:{{product.id}} </p> <p> 商品描述:{{product.title}} </p>
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { Product1Component } from './product1/product1.component'; import { ProductServiceService } from './shared/product-service.service'; import { Product2Component } from './product2/product2.component'; @NgModule({ declarations: [ AppComponent, Product1Component, Product2Component ], imports: [ BrowserModule ], providers: [ProductServiceService], bootstrap: [AppComponent] }) export class AppModule { }