Angular Service: Go get JSON! (video included)
In this exercise we will demystify the Angular Service by taking a simple pragmatic approach to implementing a service that retrieves a JSON file from the server using the HttpClientModule.
The notion of Services is that of a “Design Pattern”.
https://www.youtube.com/watch?v=GkYmMvILXzw
The notion of Services is that of a “Design Pattern”. At the end of the day a Service is nothing more than a class. What makes it fancy is combining it with Dependency Injection (DI) which handles instantiation & construction for us.
Coincidentally Services are “Singletons”. Meaning that they will only be instantiated once within the current context. By injecting a Service in multiple locations such as a parent & child component you can effectively share the state of objects.
Why should I use a service?
Anytime you want to provide re-usability at the logic level you should wrap it into a service. By de-coupling your logic from the scope of Component Classes you maintain “Separation of Concerns”. Doing so will
Declaring a Service
ng generate service
/src/app/forms.service.ts:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FormsService {
public constructor(private httpClient: HttpClient) {
}
public getFormSchema(): Observable {
let subject: Subject = new Subject();
this.httpClient.get('assets/form-schema.json').subscribe((results: any) => {
console.log(results);
subject.next(results);
});
return subject;
}
}
Consuming a Service
In this example we will use “Dependency Injection” to be able to call our services getFormSchema() method:
/src/app/ app.component.ts
import {Component} from '@angular/core';
import {FormsService} from './forms.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public constructor(private formsService: FormsService) {
formsService.getFormSchema().subscribe((results: any) => {
console.log(results);
});
}
}