Angular和rxjs – 我需要connect或refCount吗?

前端之家收集整理的这篇文章主要介绍了Angular和rxjs – 我需要connect或refCount吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上,我昨天询问了重复使用来自可观察数据的数据,然后我也在其他地方询问并阅读更多内容然后我想,为什么不只是持有一个observable并使用map运算符操作数据.

所以我只做一个HTTP请求,将observable存储到某个变量并在那里操作它.代码有效,但我不确定我是否正确使用.publishReplay(1).refCount(),还是应该使用connect?或者,我甚至需要这些吗?此外,是否有任何可能的内存泄漏可能来自此服务?

这是服务代码

@Injectable()
export class UsersApiService {

  private readonly baseUrl: string = 'https://reqres.in/api/users';
  resource$: Observable<any>;

  constructor(private http: HttpClient) {
    this.resource$= this.http.get<IUserDetails[]>(this.baseUrl).pipe(
      tap((data) => {
        console.log('"getUsers" successfully called!');
      }),map((data: any) => {
        return data.data;
      })
    ).publishReplay(1).refCount();
  }

  getUsers(): Observable<IUser[]> {
    return this.resource$.pipe(
      map((data: IUserDetails[]) => {
        return <IUser[]>data.map((u) => {
          return {
            id: u.id,name: `${u.first_name} ${u.last_name}`
          };
        });
      })
    );
  }

  getUserById(id: number): Observable<IUserDetails> {
    return this.resource$.pipe(
      map((data) => {
        return <IUserDetails>data.find(x => x.id === id);
      })
    );
  }

}

而工作示例:http://plnkr.co/edit/3S8iKbvrrGOj9netd8sM?p=preview

I’m not sure if I’m using .publishReplay(1).refCount() correctly

是的,你是.您也可以使用shareReplay(1).

or should I use connect?

当第一个订阅者出现时,refCount()已经为您连接(并且当所有观察者都取消订阅时断开连接).

do I even need any of that

如果你想把它作为一个可观察的,是的.否则,您将一遍又一遍地查询后端.但是,你当然也可以记住最后一次发射:

private resource: Observable<IUserDetails[]>;

constructor(http: HttpClient) {
    this.http.get(/* … */).subscribe(data => this.resource = data);
}

getUserById(id: number): IUserDetails {
    return this.resource.find(x => x.id === id);
}

Also,is there any possible memory leak that could come out of this service?

不,因为HttpClient完成了它的返回observable,这意味着你的多播observable的源被断开了.

原文链接:https://www.f2er.com/angularjs/240506.html

猜你在找的Angularjs相关文章