Angular Week

Abril 24 - 28, 2018

Álvaro José Agámez Licha

Senior Web UI

@codemaxter

Ingeniero en Informática, desarrollador por pasión, co-organizador de MedellinJS, dog lover, gamer, geek, nerd

Angular Observable Data Services

Angular Observable Data Services

Angular Week

Angular brings many new concepts that can can improve our JavaScript applications. The first new concept to Angular is the use of Observables. Observables are a proposed feature coming to the JavaScript specification.

Angular Observable Data Services

Angular Week

Observables can help manage async data on a easy way. Observables are similar to Promises but with a few key differences. The first is Observables emit multiple values over time. For example a Promise once called will always return one value or one error. This is great until you have multiple values over time. This is where Observables really shine.

Angular Observable Data Services

An observable data service is an Angular injectable service that can be used to provide data to multiple parts of the application. The service, that can be named a store can be injected in any place where the data is needed:

What is an Observable Data Service?

Angular Week

export class App {
  constructor(private todoStore: TodoStore, 
              private uiStateStore: UiStateStore) {
  }
}

Angular Observable Data Services

Lets look at an example where we subscribe to an Observable.

Angular Week

todosService.todos.subscribe(updatedTodos => {
  this.componentTodos = updatedTodos;
});

// OR if using the prefered async pipe 
// https://angular.io/docs/ts/latest/guide/pipes.html
this.todos = todosService.todos;

<!-- Async pipe is used to bind an observable directly in our
 template -->
<div *ngFor="let todo of todos | async">
  {{ todo.value }} <button (click)="delete(todo.id)">x</button>
</div>

Angular Observable Data Services

The heart of an observable data service is the RxJs Subject. Subjects implement both the Observer and the Observable interfaces, meaning that we can use them to both emit values and register subscribers.

 

The subject is nothing more than a traditional event bus, but much more powerful as it provides all the RxJs functional operators with it. But at its heart, we simply use it to subscribe just like a regular observable:

Angular Week

let subject = new Subject();
subject.subscribe(value => console.log('Subject value: '))

Angular Observable Data Services

Subject has one particularity that prevents us from using it to build observable data services: if we subscribe to it we won't get the last value, we will have to wait until some part of the app calls next().

 

This poses a problem especially in bootstrapping situations, where the app is still initializing and not all subscribers have registered, for example not all async pipes had the chance to register themselves because not all templates are yet initialized.

Angular Week

Angular Observable Data Services

Angular Week

What the hell can I do?

Angular Observable Data Services

Angular Week

BehaviorSubject to the rescue

The solution for this is to use a BehaviorSubject. What this type of subject does it that it will return upon subscription the last value of the stream, or an initial state if no value was emitted yet:

let behaviorSubject = new BehaviorSubject(initialState);

Angular Observable Data Services

Angular Week

How to build an Observable Data Service

@Injectable() 
export class TodoService {
  private todos: BehaviorSubject<Todo[]>; 
  private baseUrl: string;
  private dataStore: {  // This is where we will store our data in memory
    todos: Todo[]
  };
    
  // Using Angular DI we use the HTTP service
  constructor(private http: Http) {
    this.baseUrl  = 'http://56e05c3213da80110013eba3.mockapi.io/api';
    this.dataStore = { todos: [] };
    this.todos = <BehaviorSubject<Todo[]>>new BehaviorSubject();
  }

  get todos() {
    return this.todos.asObservable();
  }
}

Angular Week

Abril 24 - 28, 2018

¡Muchas Gracias!

Angular Observable Data Services

Repo: https://github.com/angular/angular

Álvaro José Agámez Licha

Senior Web UI

@codemaxter

https://coryrylan.com/blog/angular-observable-data-services

http://oomusou.io/angular/observable-data-service/

https://github.com/oomusou/NG51ObservableDataService

http://www.qingpingshan.com/m/view.php?aid=257863
https://embed.plnkr.co/jgDTXknPzAaqcg9XA9zq

https://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/

Angular Observable Data Services

By Alvaro Agamez

Angular Observable Data Services

Angular Observables Data Services Talk for Angular Week 2018

  • 645