The approach that will be discussed in this post uses the recommended HttpClient from angular 4.
login.service.ts
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'; @Injectable() export class LoginService { constructor(private http: HttpClient) { } // submitUser(obj: LoginObj): Observable{ submitUser(obj: LoginObj): Observable { return this.http.post(`${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.
login.component.ts
import {Component, OnInit} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {LoginService} from './login.service'; import {LoginObj} from './login-obj'; @Component({ 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; this.userLoginSer.submitUser(this.loginObj) .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,
login-obj.ts
export class LoginObj { message: string constructor() { } }
return-obj.ts
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.
app.module.ts
import {NgModule} from '@angular/core'; import {LoginComponent} from './login.component'; import {LoginService} from './login.service'; @NgModule({ declarations: [ LoginComponent, ...], .... providers: [ LoginService, .... ], ... }) export class AppModule { }