【问题标题】:How to create a new Observable which is subscribed to Observable returned by http.post method in angular2?如何创建一个订阅 angular2 中 http.post 方法返回的 Observable 的新 Observable?
【发布时间】:2015-10-21 12:25:24
【问题描述】:

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

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

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

如果我选择进行响应式编程并希望返回一个 Rx.Observable 作为此方法的返回值。如何创建这个 Rx.Observable 来订阅 http post observable complete 事件。

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

【问题讨论】:

  • 嘿,这似乎已在 alpha33 上修复,请参阅 changelogthis
  • 我正在使用 alpha33,但是我确实发现了如何将一个 observable 转换为另一个。谢谢:)

标签: angular typescript rxjs


【解决方案1】:

这就是我将可观察字符串附加到 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)});

【讨论】:

  • 很高兴看到您成功了。我还在学习如何使用 Observable ;_;。这肯定会有所帮助,感谢分享解决方案;)
  • 是的,我必须阅读整个 rxjs 文档,我很高兴文档很好:)
猜你喜欢
  • 1970-01-01
  • 2019-10-26
  • 2018-11-23
  • 2017-03-29
  • 1970-01-01
  • 2017-02-17
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多