0

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
  }
}

1 Answer 1

2

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks this was my thinking. apart from the above is there a way to return for example the res.json() directly back to the component without emitters? Eg In angular 2 the service would return res.json() and the component promise and .then? Or is the above the method is Angular 2 way ie keep business logic, data in Service etc
Hi I tried the above code but get the following error: Type 'EventEmitter<{}>' is not assignable to type 'EventEmitter<boolean>'. Type '{}' is not assignable to type 'boolean'. do you why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.