加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:19:08 所属栏目:安全 来源:网络整理
导读:基本上,我昨天询问了重复使用来自可观察数据的数据,然后我也在其他地方询问并阅读更多内容然后我想,为什么不只是持有一个observable并使用map运算符操作数据. 所以我只做一个HTTP请求,将observable存储到某个变量并在那里操作它.代码有效,但我不确定我是否正
基本上,我昨天询问了重复使用来自可观察数据的数据,然后我也在其他地方询问并阅读更多内容然后我想,为什么不只是持有一个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的源被断开了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读