How to create Observable function in angular

Read to understand Observable in angular What is Observable in angular.

 

Create a function in a service file that return Observable. authentication.service.ts

new Observable((observer))

public Login(email: string, password: string): Observable<any> {
    return new Observable((observer) => {
      // Clear Authorization token for API requests
      this.api.clearAuthorizationToken();
      this.api.http.all('users/login').post({email: email, password: password}).subscribe(user => {
        // Set Authorization token for API requests
        this.api.setAuthorizationToken(user.token);
        localStorage.setItem(this.TOKEN_KEY, user.token);
        observer.next(user.plain());
        observer.complete();
      });
    });
  }

 



Consume Observable in component.ts with .subscribe()

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AuthService } from '../authentication.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private authService: AuthService, private router: Router) {}

  ngOnInit() {
  }

  // On login form submit
  onSubmit() {
    this.authService.Login(this.loginForm.value.email, this.loginForm.value.password).subscribe(user => {
      console.log('value:', user);
    });
  }
}

 

 

How to create Observable function in angular
Show Buttons
Hide Buttons