【问题标题】:Angular - Why am I getting object of objects instead of array of objects?Angular - 为什么我得到对象而不是对象数组?
【发布时间】:2020-08-10 11:57:12
【问题描述】:

组件:

applicants: UserProfile[];
ngOnInit() {
    this.store
      .pipe(select(fromRootUserProfileState.getUserProfiles))
      .subscribe((userProfiles: UserProfile[]) => {
        this.applicants = userProfiles;
        console.log('this.applicants:', this.applicants);
      });
}

UserProfile 接口:

export interface UserProfile {
  id: number;
  fullName: string;
  roles?: Role[];
  windowsAccount?: string;
  firstName?: string;
  lastName?: string;
  email?: string;
  managerName?: string;
  managerId?: number;
  managerEmail?: string;
  companyId?: number;
  companyName?: string;
  countryId?: number;
  country: Country;
  countryName?: string;
}

NgRx 效果:

@Injectable()
export class UserProfileEffects {
  constructor(
    private actions$: Actions,
    private userProfileService: UserProfileService
  ) {}
  @Effect()
  loadUserProfiles$: Observable<Action> = this.actions$.pipe(
    ofType(userProfileActions.UserProfileActionTypes.LoadUPs),
    mergeMap((action: userProfileActions.LoadUPs) =>
      this.userProfileService.getUserProfiles().pipe(
        map(
          (userProfiles: Array<UserProfile>) =>
            new userProfileActions.LoadSuccessUPs(userProfiles)
        ),
        catchError((err) => of(new userProfileActions.LoadFailUPs(err)))
      )
    )
  );
}

服务:

getUserProfiles(): Observable<UserProfile[]> {
    return this.http.get<UserProfile[]>(this.baseUrl + 'userprofiles/getuserprofiles');
  }

后端 API (.Net Core):

[HttpGet("[action]")]
public async Task<IActionResult> GetUserProfiles()
{
var userProfiles = await _userProfileRepository.GetUserProfiles();
var userProfileViewModels = _mapper.Map<IEnumerable<UserProfileViewModel>>(userProfiles);

return Ok(userProfileViewModels);
}

但在组件中,我不能将我的“申请者”数组视为正确的数组,它是某种对象。这发生在我的代码中,为什么我没有得到我明确定义的对象数组?

【问题讨论】:

  • 你能发布你的控制台响应吗?
  • 我只是在最后添加了片段。
  • 正如我在响应中看到的,它不是一个数组,它的对象索引为 0,1,2 等等。您不能对对象使用推送功能。您需要检查实现,或者是否可以在 stackblitz 中发布。
  • 后端API方法也加入了。

标签: arrays angular typescript ngrx typescript-typings


【解决方案1】:

我现在可以建议解决方法。您可以从下面的代码将响应转换为数组。

for (var key in userProfiles ) {
    if (userProfiles.hasOwnProperty(key)) {
        var val = userProfiles[key];
        this.applicants.push(val)
    }
}

之后就可以对applicants变量进行push操作了。

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多