Thank you for visiting my site!


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.
[code lang=”js”] 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.
[code lang=”js” highlight=”1,14″] import { CoursesService } from "./courses.service";
import { Component, OnInit } from "@angular/core";

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) { = service.getCourses();

ngOnInit() {}

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

[code lang=”js”] providers: [CoursesService, AuthorsService],

[code lang=”js”] <h1>Courses</h1>

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