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"];
}
}
[/code]
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";
@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() {}
}
[/code]
3. Register the dependency in the app.module.
Inject the dependencies of this component into its constructor
[/code] [code lang=”js”] <h1>Courses</h1>
<h2>{{ coursesTitle }}</h2>
<ul>
<li *ngFor="let course of courses">{{ course }}</li>
</ul>
<button class="btn btn-primary">Save</button>[/code]
[/code]