CS 5220 Advanced Topics in Web Programming Angular
CS 5220 Advanced Topics in Web Programming Angular – Services Chengyu Sun California State University, Los Angeles
Services Classes that implement business logic of an application Angular can make service classes available to other parts of the application via dependency injection
How Dependency Injection Works Declare something to be injectable Determine where to inject Have some mechanism to perform injection Injectables Inject Recipients
Dependency Injection in Spring Any bean can be injected into other beans n n Annotations, e. g. @Component Bean configuration file, e. g. <bean> Any bean can receive injection n n Auto wiring (default by type) Bean configuration file, e. g. property and ref Injection means n Field, Setter, and Constructor
Dependency Injection in Angular Injectables (usually service classes and data) are either declared in providers of @Ng. Module, or decorated with @Injectable Injection via constructor Auto wiring by token
Declare Injectables in @Ng. Module Type Token providers: [ { provide: User. Service, use. Class: User. Service }, { provide: 'SECRET', use. Value: 'abcd' } ] String Token providers: [ User. Service, { provide: 'SECRET', use. Value: 'abcd' } ]
Declare Injectables Using @Injectable({ provided. In: 'root' }) export class User. Service { … } Inject using the application's root injector Angular's dependency injection system is hierarchical – injection can be done at the root, module, and component level
Constructor Injection Class Home. Component { constructor( private User. Service: user. Service, @Inject('SECRET') private secret: string ) {} }
Example: Guest. Book … App Component entries[] @Input Guest. Book Component @Output Add. Entry Component
… Example: Guest. Book App Component Guest. Book Component Add. Entry Component Data Service REST API
Guest. Book Backend A simple Node. js server application generated using Express Generator Use a global array to hold Guest. Book entries Two endpoints at /api/guestbook n n GET: get all entries POST: add an entry
Set Up Proxy During Development … Angular App NG Server at Port 4200 API Server at Port 3000 (or 8080) Localhost REST API Call Browser For security reasons, browsers enforce same-origin policy on XMLHttp. Request
… Set Up Proxy During Development … Angular App NG Server at Port 4200 REST API Call API Server at Port 3000 (or 8080) Localhost Browser
… Set Up Proxy During Development Create proxy configuration file proxy. conf. json, e. g. { } "/api": { "target": "http: //localhost: 3000", "secure": false } Change start script in package. json ng serve --proxy-config proxy. conf. json
Create Data. Service Use Angular CLI to generate a service n ng generate service <name> n Naming conventions Inject it to component classes
Use Http. Client to Access REST API Import Http. Client. Module from @angular/common/http n Provides an Http. Client service that can be used to make HTTP requests Inject Http. Client services into the service class that will use it to make REST API calls
Get Guest. Book Entries from Server In Data. Service: ? ? get. Entries(): Observable<Guest. Book. Entry[]> { return this. http. get<Guest. Book. Entry[]>('/api/guestbook'); } Send a GET request In Guest. Book. Component: Angular automatically converts the response body into an array of Guest. Book. Entry ng. On. Init() { this. data. Service. get. Entries(). subscribe(entries => { this. entries = entries; }); ? ? }
Observable and Subscription An Observable represents a value or a set of values that change over time A Subscription allows a subscriber to be notified whenever the value(s) of an observable changes
Asynchronous Programming Paradigms Callback Function for event handling Promise for something that eventually produces a single result Observable for continuously changing data / data stream
Implement Add. Entry The server API returns the newly added entry, but how do we notify Guest. Book. Component to update its display?
Implementation Strategy Keep a local entries array in Data. Service and make it observable Add the newly added entry to the local entries array after the POST call Guest. Book. Component subscribes to the local entries array to automatically get the new data when the array changes
A Bit More Rx. JS Observer Observable Subject A Subject is a special type of Observable that allows values to be multicasted to many Observers. Observer … … Observer
Some Subject Methods next(value) emits the next value error(err) emits an error complete() indicates that the data stream has ended and all subscribers are unsubscribed
Behavior. Subject What if some subscriber comes in late (i. e. after some values are already emitted)? Behavior. Subject is a type of Subject that keeps the latest value n vs Replay. Subject
Readings Angular Http. Client Guide Rx. JS Overview
- Slides: 25