【问题标题】:RxJs map operator to change the property value of a collection of objects in angularRxJs map 运算符以角度更改对象集合的属性值
【发布时间】:2021-09-16 11:52:21
【问题描述】:

在我的角度组件中,我具有以下属性:

memberInfoLists$: Observable<MemberInfo[]>;
total$: Observable<number>;
memberPhotoUrl: string = environment.memberPhotoUrl;
memberDefaultPhoto: string = environment.defaultPersonPhoto;

现在在 ngOnInit 函数中,我调用了该服务来获取可观察对象来填充 memberInfoLists$ 属性。但在填充之前,我想更改集合中每个对象的属性值之一。这是我的代码:

ngOnInit(): void {
        this.memberInfoLists$ = this.service.memberInfoLists$.pipe(map(item => item.forEach(y => {
            if (y.MemberPhotoUrl) {
                y.MemberPhotoUrl = this.memberPhotoUrl + y.MemberPhotoUrl;
            }   
            else{
                y.MemberPhotoUrl = this.memberDefaultPhoto;
            }   
            
            if (y.VoterPhotoUrl) {
                y.VoterPhotoUrl = this.memberPhotoUrl + y.VoterPhotoUrl;
            }   
            else{
                y.VoterPhotoUrl = this.memberDefaultPhoto;
            }   

            return item;
        })));
        this.total$ = this.service.total$;
    }

但它会引发以下异常:

src/app/setup-module/pages/member-info-list/member-info.component.ts:69:3

  • 错误 TS2322:类型“Observable”不可分配给类型“Observable”。类型“void”不可分配给类型 '会员信息[]'。

    this.memberInfoLists$ = this.service.memberInfoLists$.pipe(map(item => item.forEach(y => {

谁能帮我解决这个问题?

【问题讨论】:

    标签: angular rxjs rxjs-observables rxjs-pipeable-operators


    【解决方案1】:

    return 语句在错误的位置,它应该在 forEach 之后

    forEach 周围应该有大括号

    this.memberInfoLists$ = this.service.memberInfoLists$.pipe(
          map((item) => {
            item.forEach((y) => {
              if (y.MemberPhotoUrl) {
                y.MemberPhotoUrl = this.memberPhotoUrl + y.MemberPhotoUrl;
              } else {
                y.MemberPhotoUrl = this.memberDefaultPhoto;
              }
    
              if (y.VoterPhotoUrl) {
                y.VoterPhotoUrl = this.memberPhotoUrl + y.VoterPhotoUrl;
              } else {
                y.VoterPhotoUrl = this.memberDefaultPhoto;
              }
            })
            return item;
          }
          )
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-03
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多