Angular Services - Quick and Dirty

Angular Services (Quick & Dirty)

Whenever I'm stubbing out an Angular site and need to setup formatting some results from a service call I'll use the code below.

//Services (Typescript file - actual service file)

//courses.service.ts

//this code is a quick and dirty service with values hard coded in an array.

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


//Services (Typescript file - component consuming the service's data)

//courses.component.ts

/*the code below is the component that consumes the data from the courses service 
(from the code above)*/

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

@Component({
  selector: 'app-courses',
  templateUrl: './courses.component.html',
  styleUrls: ['./courses.component.css']
})
export class CoursesComponent implements OnInit {
  courses; 
  /*using dependency injection "inject" the CoursesService into the 
  constructor (creating an instance of the service)*/
  constructor(service: CoursesService) { 
    //make your call to the specific method needed
    this.courses = service.getCourses();
    }
  ngOnInit() {}
}


<!--Services (HTML file to output the service calls response)-->

<!--courses.component.html-->

<!--the code below is the html that displays the service call's data response-->

Courses!<br>

<div style="text-align: left;">
    List of Courses:
    <ul>
        <li *ngFor="let course of courses">
         {{course}}
        </li>
    </ul>
</div>


Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/angular/angular-services-quick-and-dirty/