Angular Concepts
Component
A component’s job is to focus on the user experience and nothing more.
It provides properties and methods for data binding in order to mediate between the view and the application logic.
The application logic is usually associated with a data model.
Service
A service focuses on non-view related processing, such as communication with a web server.
A component can delegate certain tasks to a service such as fetching data, validating user input or logging.
By using injectable service classes, these services are available to any component. Use the
@Injectable()
decorator to allow it to be injected into a component.A service stub can be created with the command
ng generate service hero\HeroService
1@Injectable({
2 providedIn: 'root'
3})
4
5export class HeroService {
6
7 constructor(private messageService: MessageService) { }
8
9 getHeroes(): Observable<Hero[]> {
10 // TODO: send the message after fetching the heroes
11 this.messageService.add('HeroService: fetched heroes');
12 return of(HEROES);
13 }
14}
The code above show an example of a service. Each service must have at least one provider, in this case root
.
Observables
The observer pattern is a software design pattern that allows for event handling and asynchronous programming.
The subject maintains a list of dependants or observers and notifies them of state changes.
The observer subscribes to the subject’s published values to be notified of any state changes.
The state change is only executed if the observer subscribes to the subject’s state change
subscribe()
method.
Usage
The publisher creates a new instance of
Observable
that defines the subscriber function.This function is executed when the subscriber / consumer calls the
subscribe()
method.