简体   繁体   English

我如何拦截一个可观察对象以获取值并仍然返回一个可观察对象?

[英]how do i intercept an observable to get the value and still return an observable?

I was writing a sign in function in angular service that returns an observable.我在 angular 服务的 function 中写了一个标志,该服务返回一个可观察的。 I want to intercept the stream, get the value and set to variable without subscribing.我想拦截stream,获取值并设置为变量而不订阅。 i tried to use pipe and map operator and didn't work.我尝试使用 pipe 和 map 运算符但没有用。 what's the best approach to do this?这样做的最佳方法是什么?

import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
 
@Injectable({
  providedIn: 'root',
})
export class AppService {
  signInUrl: string = 'http://localhost:3000/api/v1/users/login';
  user: any;
  constructor(private _http: HttpClient) {}
 
  getUser(): Observable<any> {
    return of(this.user);
  }
 
 signIn(obj): Observable<any> {
    return this._http.post(this.signInUrl, obj).pipe(
      map((u) => {
        this.user = u;
      })
    );
  }
 
  logOut(): void {
    this.user = null;
  }
}

Your code should work, its just not getting triggered.您的代码应该可以工作,只是没有被触发。 I think you forgot to subscribe to the method.我想你忘了订阅这个方法。

For example: signIn(obj).subscribe();例如:signIn(obj).subscribe(); should do the trick.应该做的伎俩。

I think what you have to do is change 'map' with 'tap'我认为您要做的就是用“点击”更改“地图”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM