Categories
Uncategorized

Create an Observable the right way – Angular 5

Using a subject to create an observable is the recommended method of inter-component communication by the official angular documentation.
The following code was tested with Angular 5.2.2.

user.service.ts

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class LoginService {
    private user = new Subject<boolean>();
    user$ = this.user.asObservable();
   
    constructor() {
        this.user.next(true);
    }

    setUser(flag: boolean): void {
        this.user.next(flag);
        this.userNormal = flag;
    }

}

user.component.ts

import {Component, OnDestroy} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
import 'rxjs/add/operator/finally';

import {UserService} from './user.service';

@Component({
    selector: 'user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnDestroy {

    private subscription: Subscription;

    constructor(private userSer: UserService) {
     userSer.setUser(true); 
     this.subscription = userSer.user$
            .finally(() => {
                // executes eventually irrespective of the outcome.
            })
            .subscribe(data => {
                console.log(data);
            }, err => {
                console.log(err);
            }, () => {
                // on success complete.
                    });
    }

     ngOnDestroy() { 
        this.subscription.unsubscribe();
        // To avoid memory leaks when this component is destroyed.    
     }
}

Output

true