【问题标题】:How can we add another subscribe action in the http observable in angularjs2?我们如何在 angularjs2 的 http observable 中添加另一个订阅操作?
【发布时间】:2016-04-14 02:22:44
【问题描述】:

我是 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;

  }
}

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    如果你让你的 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
            () => {}  
          )
      }
    }
    

    【讨论】:

    • 您还可以使用add() 方法向subscribe() 方法返回的订阅者添加另一个订阅。 Example,但我相信我们应该习惯返回 obeservables 的服务(:
    • 非常感谢您的澄清! @Sasxa,我想知道(error) 不知何故我变得像e {_body: "{"error":"User was not found."}", status: 404, statusText: "Ok", headers: e, type: 2…}。如何从那里获得错误消息“找不到用户”?谢谢!
    • 成功和错误处理程序都有Response作为参数,你可以调用它的json()方法来获取消息
    • 感谢您的回复。我也是这么想的。在上面的 utils.service.ts 中,我在返回行的末尾添加了.map((res: Response) => res.json())。我设法将成功返回 (data) 作为 JSON 对象。但是,不知何故,error 仍然返回一个响应。有什么我应该做的吗?再次感谢!
    • 您可以使用.do 直接在 UserService 登录方法中设置访问令牌(正如 OP 尝试做的那样),而不必从 LoginComponent 再次调用该服务: return this._utils.api(request).map(res => res.json()).do(data => this.setAccessToken(data.token));。然后 LoginComponent 像往常一样订阅。
    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多