Tuesday, 5 September 2017

Using observable or subscribe in angular 2 or 4




Services=> loginServices.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/throw';
import { Observable } from "rxjs/Rx";

@Injectable()
export class loginServices
{
        constructor(private _http: Http, private _router : Router) { }
login(obj:logininfo) :Observable<logininfo>
 {   
     let _headers = new Headers({ 'Content-Type': 'application/json' });
     return this._http.post('http://localhost:53656/api/Login/checklogin', obj, { headers: _headers })
    .map((res:Res) => <logininfo>res.json()); 
    .catch(this.handleError);      
}

handleError(error:Res)
{
    console.error(error);
    return Observable.throw(error)
}


Controller:

import { Component,OnInit } from '@angular/core';
import { loginServices} from '../login.services';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { logininfo } from '../login.interface';

@Component({
  templateUrl: '../../UI/Dashboard/Login.component.html',
  styleUrls: ['../../Content/Css/master.css'],
  providers: [loginServices,logininfo]
})
export class LoginComponent implements OnInit {
msg:string;
info:any;
constructor(public _lservices:loginServices)
ngOnInit()
   {
       let data:logininfo=> new logininfo(); 
      this._lservices.login(data).subscribe(
       (logininfo )=>{
                  if(logininfo ==null)
                   {
                      this.msg="User doesn't exist"
                   }
                  else
                  {
                      this.info=logininfo;
                  }
       },
       (error)=>{
                 this.msg="Some problem with the service. Please try again after some time".
          }
       )
    
   }
}

















No comments:

Post a Comment