×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Nilesh Yadav
Added: Jun 14, 2017 12:37 PM
Modified: Jun 19, 2017 9:39 AM
Views: 9
Tags: no tags
  1. ----------
  2. File Name : employee.service.ts
  3. ----------
  4.  
  5. import {Injectable} from '@angular/core';
  6. import {Http, Headers, Response} from '@angular/http';
  7. import {Observable} from 'rxjs/Observable';
  8. import 'rxjs/add/operator/map';
  9. import 'rxjs/add/operator/catch';
  10. import 'rxjs/add/observable/throw';
  11. @Injectable()
  12. export class LoginService {
  13.     private _url: string = "http://suryodaybank.local/jsondata/login.json";
  14.     constructor(private _http: Http) {}
  15.     getLogin() {
  16.  
  17.         var username = "Admin";
  18.         var password = "A3y@Afsc1";
  19.  
  20.         var postData = "username=" + username + "&password=" + password;
  21.  
  22.         var headers = new Headers();
  23.         headers.append('Content-Type', 'application/x-www-form-urlencoded');
  24.  
  25.  
  26.         return this._http.post(this._url, postData, {
  27.             headers: headers
  28.         })
  29.         .map((response: Response) => response.json())
  30.         .catch(this._errorHandler);
  31.     }
  32.     _errorHandler(error: Response) {
  33.         console.error(error);
  34.         return Observable.throw(error || "server error");
  35.     }
  36. }
  37.  
  38. =============
  39. How to use services
  40. ---------------
  41. export  class emplist implements OnInit {
  42.        
  43. employees=[];
  44. errorMsg:string;
  45.  
  46. constructor(private _empservice: empService){}
  47. ngOnInit()
  48. {
  49.    this._empservice.getEmployees().subscribe(resdata => this.employees = resdata,
  50.             reserror => this.errorMsg = reserror,() => this.saveLoginData());
  51. }
  52.  
  53. saveLoginData() {
  54.         console.log(this.employees);
  55. }
  56.  
  57. }