我们如何在angularjs2中的http observable中添加另一个订阅操作?

时间:2016-01-09 12:18:22

标签: typescript angular

我是Angular2的新手。我有一个LoginComponent,它从提交按钮接受一个名为submitLogin的动作。单击时,它会将用户名和密码(通过UserService)发送到API服务器(在UtilService的帮助下)。如果服务器响应OK,它将返回一个令牌,我们将在本地保存并重定向它。

到目前为止,我已设法发送用户名和密码并保存令牌。但是,我对如何在LoginComponent中添加其他操作感到困惑,以便我们可以重定向用户。 (我在下面的login.component.ts中添加了一条评论,以澄清我想做的事情。)

如果我不清楚,请随时告诉我。

以下是我的代码:

login.component.ts具有以下内容:

import {Component, OnInit} from 'angular2/core';
import {NgForm}    from 'angular2/common';
import {UserService} from '../services/user.service';

@Component({
  selector: 'login',
  templateUrl: './components/login/login.component.html',
  styleUrls: ['./components/login/login.component.css']
})
export class LoginComponent implements OnInit {
  public username: string;
  public password: string;
  public loginResult: string;

  constructor(private _userService: UserService) {}
  ngOnInit() { }
  submitLogin() {
    var p = this._userService.login(this.username, this.password);
    // HOW TO: 
    // I know p is an observable. But, is it possible to add a condition as follow:
    // if p is success, then redirect
    // if p failed, then return
  }
}

user.service.ts:

import {Injectable} from 'angular2/core';
import {UtilsService} from './utils.service';

@Injectable()

export class UserService {
  constructor(private _utils: UtilsService) { }

  login(username: string, password: string) {
    var request = {
      method: 'POST',
      headers: { 'Authorization': 'Basic ' + btoa(username + ':' + password) },
      url: '/auth/',
      data: null
    };

    return this._utils.api(request).subscribe(
      data => this.setAccessToken(data.json().access_token),
      err => console.log(err)
    );
    var promise = this._utils.api(request);
    promise.then((response) => {
      this.setAccessToken(response.token);
    });
  }

}

utils.service.ts:

import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';

@Injectable()

export class UtilsService {
  private apiUrl: string;
  constructor(public http: Http) {
    this.apiUrl = '/api/1';
  }
  api(request: any) {
    var headers = new Headers();
    var url = this.apiUrl + request.url;

    if(request.headers) {
      for(var key in request.headers) {
        headers.append(key, request.headers[key]);
      }
    }

    if(!request.type || request.type === 'GET') {
      return this.http.get(url, { headers: headers });
    }

    if(request.type === 'POST') {
      return this.http.post(url, request.data, { headers: headers });
    }

    if(request.type === 'PUT') {
      return this.http.put(url, request.data, { headers: headers });
    }

    if(request.type === 'DELETE') {
      return this.http.delete(url, { headers: headers });
    }
    return false;

  }
}

1 个答案:

答案 0 :(得分:9)

如果你让UserService.login()返回observable(不是订阅者,就像现在一样),你可以在LoginComponent中订阅它

export class UserService {
  login(username: string, password: string) {

    return this._utils.api(request)
      .map(response => response.json())
    );
  }
}

export class LoginComponent implements OnInit {
  submitLogin() {
    var p = this._userService
      .login(this.username, this.password)
      .subscribe(

        // success
        (data) => { 
          this._userService.setAccessToken(data.access_token); 
          // redirect here...
        }, 

        // error
        (error) => {}, 

        // completed
        () => {}  
      )
  }
}