Ka Tech
Ka Tech

Reputation: 9457

Angular 2 - How to handle HTTP responses in Component

New to Angular 2, still trying to get my head around certain things. Where I am stuck is I have login service and login component. I send a login request from the login component to the login service to post the username and password to a login API. If successful it posts the token to the localstorage. Where I am stuck is after the token is sent storage I want to return a boolean response back to the login component. Based on the boolean response it will perform execute a function in the component.

I can do everything until I get the response. I don't know how to handle a response back to the login component. Appreciate if someone could point me in the right direction. My code as follows:

LOGIN SERVICE

import { Injectable } from '@angular/core';
import { Token } from './login';
import { APIDOMAIN } from '../../../shared/api';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class LoginService {
  url: string = APIDOMAIN;
  constructor(private http: Http) { }
  login(username: string, password: string) {
    console.log('Login API');
    let headers = new Headers();
    let data = null;
    headers.append("Authorization", "Basic " + btoa(username + ":" + password)); 
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    this.http.post(this.url+ '/login', data, {headers: headers})
    .map(res => res.json())
    .subscribe(
      token => { console.log(token); localStorage.setItem('id_token',token.token); },
      err => { console.log(err);},
        () => console.log('Request Complete')
    );
  }
  logout(): void {
    localStorage.removeItem('id_token');
  }
}

LOGIN COMPONENT

import { Component, OnInit } from '@angular/core';
import { LoginService } from './shared/login.service';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  username: string;
  password: string;
  constructor(private loginService: LoginService) { }
  ngOnInit() {}
  login(): void {
    this.loginService.login(this.username,this.password)
    // PEFORM SOME FUNCTION BASED BOOLEAN RESPONSE
  }
}

Upvotes: 0

Views: 1410

Answers (1)

Sasxa
Sasxa

Reputation: 41274

Here's one solution:

export class LoginService {
  status: EventEmitter<boolean> = new EventEmitter();

  login(username: string, password: string) {
    this.http.post(...)
    .map(res => res.json())
    .subscribe(token => { 
      console.log(token); 
      localStorage.setItem('id_token',token.token); 

      this.status.emit(true);

      });

  logout() {
    localStorage.removeItem('id_token');

    this.status.emit(false);
  }
}


export class LoginComponent implements OnInit {

  constructor(private loginService: LoginService) { }

  ngOnInit() {

    this.loginService.status.subscribe(console.info);
  }
}

Upvotes: 2

Related Questions