HTTP call in Angular 5

The approach that will be discussed in this post uses the recommended HttpClient from angular 4.


import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

import {LoginObj} from './login-obj';
// import {ReturnObj} from './return-obj';
import {baseUrl} from '../backend';

export class LoginService {
    constructor(private http: HttpClient) {

    // submitUser(obj: LoginObj): Observable {
    submitUser(obj: LoginObj): Observable {
        return`${baseUrl}login.php`, obj);

The above login service returns an observable of type any. We can also validate the object being returned by expecting a certain class.
Now the service needs to be injected into the component that we are going to use.


import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';

import {LoginService} from './login.service';
import {LoginObj} from './login-obj';

    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
export class LoginComponent implements OnInit {

    loading = false;
    errorMessage = '';
    successMessage = '';
    loginObj = new LoginObj();
    constructor(private userLoginSer: LoginService) {}

    ngOnInit(): void {}

    onLoginSubmit(): void { 
            this.loading = true;
                .finally(() => {
                    // This does exactly what it says, it executes finally irrespective of success, failure.
                    this.loading = false;
                .subscribe(returnObj => {
                   this.successMessage = 'Hurray!';
                    error => {
                        this.errorMessage = 'Sorry! Something went wrong!';
                      () => {  
                       // onComplete
                       // This runs only if it is a success and after the code in the success block.

The login and return classes may look somewhat like this,


export class LoginObj {
    message: string
    constructor() {


export class ReturnObj {
    message: string
    constructor() {

Now we finally need to add the service and component into the app.module.ts.

The service goes into the providers section, and the component goes into the declarations.


import {NgModule} from '@angular/core';

import {LoginComponent} from './login.component';
import {LoginService} from './login.service';

    declarations: [
    providers: [

export class AppModule {