Thank you for visiting my site!

Services

1. Create a service
Components should do only presentation logic.
Use services to separate logic from Component, and to re-use the http call in multiple components.

 
export class CoursesService {
  getCourses() {
    return ["course1", "course2", "course3"];
  }
}

2. Use it:
add a parameter instance of class service in the constructor, angular will instantiate a new service object.

  
import { CoursesService } from "./courses.service";
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-courses",
  templateUrl: "./courses.component.html",
  styleUrls: ["./courses.component.scss"]
})

export class CoursesComponent implements OnInit {
  coursesTitle = "List of courses";
  courses: any;

  constructor(service: CoursesService) {
    this.courses = service.getCourses();
  }

  ngOnInit() {}
}

3. Register the dependency in the app.module.
Inject the dependencies of this component into its constructor

 providers: [CoursesService, AuthorsService],
 
<h1>Courses</h1>

<h2>{{ coursesTitle }}</h2>
<ul>
  <li *ngFor="let course of courses">{{ course }}</li>
</ul>
<button class="btn btn-primary">Save</button>
[/code]

ADD YOUR COMMENT