Angular 使用角度中的异步管道设置选择元素的选定项

Angular 使用角度中的异步管道设置选择元素的选定项,angular,rxjs,rxjs-observables,async-pipe,Angular,Rxjs,Rxjs Observables,Async Pipe,角度专家!我试图理解Angular中的异步管道,但我被困在一个基本场景中。我在UI中有两个select元素,一个包含帖子,另一个包含相关评论。我想设置一个帖子(最后一个)作为显示帖子的select元素的初始选择,并且我想使用所选项目在第二个select中过滤相关评论。这在我的代码中不起作用,为此我在Stackblitz中创建了一个简化版本: 你们谁能解释一下我做错了什么?这是相关的代码片段和HTML: ngOnInit() { this.postList$ = this.getPost

角度专家!我试图理解Angular中的异步管道,但我被困在一个基本场景中。我在UI中有两个select元素,一个包含帖子,另一个包含相关评论。我想设置一个帖子(最后一个)作为显示帖子的select元素的初始选择,并且我想使用所选项目在第二个select中过滤相关评论。这在我的代码中不起作用,为此我在Stackblitz中创建了一个简化版本:

你们谁能解释一下我做错了什么?这是相关的代码片段和HTML:

ngOnInit() {
    this.postList$ = this.getPostList();

    // latestPost$ is not is use yet, but maybe it could be used to set the selected post?
    this.latestPost$ = this.postList$ 
      .pipe(
        map(posts => posts[posts.length - 1])
      );

    this.selectedPost$ = combineLatest([
      this.postList$,
      this.postSelectedAction$
    ])
      .pipe(
        map(([posts, selectedPostId]) => posts.find(post => post.id === selectedPostId))
      );

    this.commentList$ = this.selectedPost$
      .pipe(switchMap(
        post => this.getCommentList(post)
      ));
  }


<select [ngModel]="selectedPost$ | async" (change)="onSelected($event.target.value)">
  <option *ngFor="let post of postList$ | async" [ngValue]="post">
    {{post.id}} {{post.title}}
  </option>
</select>
<select>
  <option *ngFor="let comment of commentList$ | async" [ngValue]="comment">
    {{comment.id}} {{comment.postId}} {{comment.name}}
  </option>
</select>
ngOnInit(){
this.postList$=this.getPostList();
//latestPost$尚未使用,但是否可以用于设置所选的帖子?
this.latestPost$=this.postList$
.烟斗(
映射(posts=>posts[posts.length-1])
);
此.selectedPost$=CombineTest([
此.postList$,
这是postSelectedAction$
])
.烟斗(
map(([posts,selectedposted])=>posts.find(post=>post.id==selectedposted))
);
this.commentList$=this.selectedPost$
.管道(开关图)(
post=>this.getCommentList(post)
));
}
{{post.id}{{post.title}}
{{comment.id}{{comment.postId}{{comment.name}

默认情况下,Angular通过引用比较对象

你就快到了。问题是,您的
select
会获得一个
选项的列表,这些选项引用
Post
s作为
ngFor
的一部分。现在,为了找出当前选择了哪个
选项
,Angular将每个
post
对象与
selectedPost$| async
的当前值进行比较

默认情况下,操作方法是使用
=
操作符。
=
操作符按值比较基本体,但按引用比较对象。例如:

console.log('a'='a');
常量obj={'a':'b'};
常数obj2=obj;
console.log(obj==obj2);

log(obj==={'a':'b'})谢谢fjc,它工作得很好,我学到了一些新东西!我可以问一下,当我在第一个选择中选择一篇文章时,你是否能够发现为什么第二个选择(评论)没有更新?不客气。就我所见,注释选择没有更新,因为您没有将它与任何值连接起来。对于post select,您有一个ngModel集。对于你的评论选择,没有这样的事情。你是对的,我计划添加一个ngModel来获取所选评论,但现在我只希望评论列表由所选帖子过滤。正如你在第38行看到的那样,我正试图用一个开关地图来实现这一点。我想这不是办法。你有更好的建议吗?我自己发现的。我希望onSelected中的输入参数错误。再次感谢你无价的帮助!很好,很高兴你这么做了。我还没有机会去看看。不客气,很高兴看到一个写得好、清楚的问题,以及一个实际可重复的问题。