import { Injectable } from '@angular/core'; @Injectable()
export class ProductServiceService { constructor() { } getProduct(): Product {
return new Product(, "iPhone7");
} } export class Product {
constructor(
public id: number,
public title: string
) { }
}
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'; @NgModule({
declarations: [
AppComponent,
Product1Component
],
imports: [
BrowserModule
],
providers: [ProductServiceService],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component, OnInit } from '@angular/core';
import { ProductServiceService, Product } from '../shared/product-service.service'; @Component({
selector: 'app-product1',
templateUrl: './product1.component.html',
styleUrls: ['./product1.component.css']
})
export class Product1Component implements OnInit { product: Product; constructor(private productService: ProductServiceService) { } ngOnInit() {
this.product = this.productService.getProduct();
} }
<p>
商品Id:{{product.id}}
</p>
<p>
商品描述:{{product.title}}
</p>