Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用rxjs组合两个观测值_Rxjs - Fatal编程技术网

用rxjs组合两个观测值

用rxjs组合两个观测值,rxjs,Rxjs,我有一个应用程序,用户可以调用2个操作: 获取项目列表 添加项 对于这两个操作,视图应显示当前项目。 使用rxjs操作符有什么优雅的方法吗 目前的执行情况: ngOnInit(): void { this.getItems(); } addItem = () => { this.addedItem$ = this.httpClient.post(url, { name: 'foo'} ).subscribe(() => {

我有一个应用程序,用户可以调用2个操作:

  • 获取项目列表
  • 添加项
对于这两个操作,视图应显示当前项目。 使用rxjs操作符有什么优雅的方法吗

目前的执行情况:

ngOnInit(): void {
    this.getItems();
    }

addItem = () => {
    this.addedItem$ = this.httpClient.post(url,
      { name: 'foo'}
    ).subscribe(() => {
        this.getItems();
      });
  }

 private getItems() {
    this.items$ = this.httpClient.get(url);
  }
模板:

<div *ngFor="let item of items$ | async">
    {{item.name}}
  </div>

{{item.name}
我不想每次添加新项目时都获取所有项目的列表。
如果我可以将两个流组合在一起,效果会更好。

您可以将获取的项目存储在普通js数组中,而不是使用可观察对象。添加新项后,您可以将新项推送到该数组中

items = [];

ngOnInit(): void {
  this.getItems();
}

addItem = () => {
  const item = { name: 'foo'};
  this.httpClient.post(url, item)
      .subscribe(() => this.items.push(item));
}

private getItems() {
  this.httpClient.get(url)
      .subscribe(items => this.items = items)
}


<div *ngFor="let item of items">
  {{item.name}}
</div>

所以,如果我理解正确的话,您希望加载项目列表,还希望有某种形式(或相同视图中的任何形式),将新项目添加到列表中,并向服务器发出“post”请求。另外,您不想在每次添加新项目时发出新的get请求吗?如果我理解正确,我想问你你有权更改
post
请求的服务器响应吗?我可以更改post-responseAnks,但我想使用observable来编辑我的答案,你可以使用作为observable子类型的
BehaviorSubject
来实现
  items = new BehaviorSubject<any>([]);

  ngOnInit(): void {
    this.getItems();
  }

  addItem = () => {
    const item = { name: 'foo'};
     this.httpClient.post(url, item)
        .subscribe(() => this.items.next([...this.items.value, item]));
  }

  private getItems() {
    this.httpClient.get(url)
        .subscribe(items => this.items.next(items))
  }

  <div *ngFor="let item of items | async">
    {{item.name}}
  </div>