Why service?

Components should not directly fetch or save data, and they should not know if they are displaying fake data. They should focus on presenting data and delegate responsibility for data access to a service.

This time you’ll create a XuxuService and inject it into the ServeDemoComponent constructor using Angular dependency injection.

Services are a great way to share information between classes that “don’t know each other.”

1. Create a service

Enter:

Ng Generate service Name of the serviceCopy the code

I input the following, that is, my service name is xuxu:

ng generate service xuxu
Copy the code

After this command is executed, XuxuService is automatically generated in SRC /app/xuxu.service.ts

2. Obtain data in XuxuService (xuxu.service.ts)

  1. Import the class class
import { XuxuClass } from './xuxu-class';
Copy the code
  1. Add methods to return data
export class XuxuService {

  constructor() { }
  getXuxuTestMock(): XuxuClass[] {
	letData = [1, 2, 3]returndata; }}Copy the code

XuxuService

Enter:

Ng generate service --module=appCopy the code

Create a page component

ng generate component service-demo
Copy the code

Five, use in components

  1. Service-demo.component.ts page Service-xuxu service data:
import { Component, OnInit } from '@angular/core';
import { XuxuService } from '.. /xuxu.service';

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

  constructor(private xuxuService: XuxuService) { }

  ngOnInit() {// call getXuxuTestMock this.getXutestMock (); } / / initialization xuxuTestMock xuxuTestMock getXuxuTestMock () : void {this. XuxuTestMock = this. XuxuService. GetXuxuTestMock (); console.log('xuxuTestMock:', this.xuxuTestMock)
  }
}
Copy the code
  1. Service-demo.component.html page displays the data service-service-received:
</h2> <ul> <li *ngFor="let i of xuxuTestMock" (click)="test(i)">{{i.name}}</li>
    </ul>
</div>
Copy the code