创建observable,订阅并返回它

时间:2017-07-12 09:32:32

标签: angular rxjs reactive-programming

我有以下问题: 我需要发送POST请求以从oAuth获取令牌。后来我想通过其他服务创建用户上下文。但我仍然需要保留Observable,因为我想对组件的响应做出反应。

这是一种正确的方法吗?

login(username, password): Observable<any> {
  let response$ = this._http.post(params)
    .map((response: Response) => response.json());

  response$.subscribe(v => this._userService.doSmth());

  return response$;
}

修改

我找到了另一种基于@Maximus响应的方法。那是对的 - 我只想做一个请求。所以我写了这样的话:

let response$ = this._http.post(data)
  .map((response: Response) => response.json());

let user$ = new Subject<User>();

response$.subscribe(v =>
  this._userService.createNewSession(v) // returns observable
    .subscribe(u => user$.next(u))
);

return user$.asObservable();

这可以吗?

1 个答案:

答案 0 :(得分:2)

此代码:

let response$ = this._http.post(params).map((response: Response) => response.json());

设置一个可观察的链,它本身不做任何事情。只要有人订阅它就会发送http请求。这就是这里发生的事情:

response$.subscribe(v => this._userService.doSmth());

但是response$指向该链,而不是返回的值。如果其他人再次订阅response$,则会发出新请求。

如果您想允许订阅response$并希望系统的其他部分能够访问该值,则应使用AsyncSubject

let subject = new AsyncSubject();
let response$ = this._http.post(data).map((response: Response) => response.json()).subscribe(subject);
response$.subscribe(v => this._userService.createNewSession(v));

return response$;
相关问题