Angular 2 - 如何在Component中处理HTTP响应

时间:2016-10-14 03:15:08

标签: http angular

Angular 2的新手,仍然试图绕过某些事情。我被困的地方是我有登录服务和登录组件。我将登录组件的登录请求发送到登录服务,以将用户名和密码发布到登录API。如果成功,它会将令牌发布到localstorage。我被卡住的地方是在令牌被发送存储之后我想要将一个布尔响应返回给登录组件。基于布尔响应,它将执行组件中的执行功能。

在得到回复之前,我可以做任何事情。我不知道如何处理回登录组件的响应。感谢有人能指出我正确的方向。我的代码如下:

登录服务

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');
  }
}

登录组件

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 个答案:

答案 0 :(得分:2)

这是一个解决方案:

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