angular - 如何创建一个新的Observable,它订阅了angular2中http.post方法返回的Observable?

标签 angular typescript rxjs

我正在创建一个 Angular2 服务。我使用了 http.post 方法,该方法返回 EventEmmiter,并根据我接下来传递的文档并返回 lambda。 https://angular.io/docs/js/latest/api/http/Http-class.html

下一个 lambda 按预期工作,但返回 lambda 根本没有被调用。

当我尝试返回 this.user 时。由于后期操作尚未完成,因此它为空。在身份验证响应返回之前我应该​​做什么才能等待。

如果我选择进行响应式(Reactive)编程并希望返回 Rx.Observable 作为此方法的返回。我如何创建这个 Rx.Observable 它将订阅 http post observable 完成事件。

@Injectable()
export class LoginService {

  http:Http;
  headers:Headers;
  user:User;

  constructor(http: Http) {
    this.http=http;
    this.headers=new Headers();
    this.headers.set('Content-Type','application/json');
    this.user = new User();
  }

  authenticateUser(credential:Credential) {
    credential.type = 'normal';
    this.http.post('http://localhost:8000/api/v1/auth',
      JSON.stringify(credential),
      {
        headers: this.headers
      }
    ).observer({
      next: (res) => {
        if(res.json()._error_type){
          console.log('Error Occured');
        }
        console.log(res.json());
        this.user.authToken = res.json().auth_token;
      },
      return: () => {
        console.log("Logged In");
        return "LoggedIn Success"
      }}
    );
    console.log(this.user);
    return this.user;
  }
}

export class User{
  authToken:String;
}

export class Credential{
  username:string;
  password:string;
  type:string;
}

最佳答案

这就是我将可观察到的字符串附加到http调用响应的方式

  authenticateUser(credential:Credential):Rx.Observable<string> {
    credential.type = 'normal';
    return Rx.Observable.create<string>(
      observer => {
        var val:String;
        this.http.post('http://localhost:8000/api/v1/auth',
          JSON.stringify(credential),
          {
            headers: this.headers
          }
        ).toRx().map(res => res.json()).subscribe(
        (res) => {
          if(res._error_type){
            console.log('Error Occured');
            observer.onError('ErrorOccured');
          } else {
            this.user = new User();
            this.user.authToken = res.auth_token;
            observer.onNext('LoginSuccess');
          }
          observer.onCompleted();
        });
        return () => console.log('disposed')
      }
    );
  }

这是调用 LoginService 的 UI 组件

this.loginService.authenticateUser(credential).subscribe(val => {console.log('result:' + val)});

关于angular - 如何创建一个新的Observable,它订阅了angular2中http.post方法返回的Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718807/

相关文章:

javascript - Angular http 发布错误 : Cannot read property 'post' of undefined

angular - Karma 断开连接,因为 10000 毫秒内没有消息

typescript - Guards 和循环依赖中的服务注入(inject)

angular - 可观察的 forkJoin 未触发

angular - 未安装 Ionic Firebase 插件

node.js - bootstrap.css 没有出现在浏览器中

javascript - 如何使用jsdom测试 'document'的函数

javascript - Angular 6 Material MatFormField 显示为未知组件

reactjs - React + Redux-Observable 超时大理石测试

javascript - 在 Angular 中使用 rxjs 进行双向数据绑定(bind)