无法在 Angular 的 subscribe() 函数内分配对象的属性

Can't assign object's properties inside the subscribe() function in Angular

我定义了 prsnlStateInterface 类型的对象 persnel 并试图通过订阅一个可观察对象来分配属性失败。这是 persnels 定义:

 persnels : prsnlStateInterface = {
    id :'',
    firstname:'',
    lastname : '',
    fullname :'',
    profession : '',
    dob : '',
    nationality: '',
    createdDate: '',
    sex: '',
    gender :'',
    phone :0,
    adresse : '',
    prsnlRoleIds : [0],
    total :0,
    selectedUserId :0,
    ids :[] ,
    entities :{},
  }

这是 prsnlStateInterface:

export interface prsnlStateInterface {
    "id": String,
    "firstname": String,
    "lastname": String,
    "fullname": String,
    "profession": String,
    "dob": String,
    "nationality": String,
    "createdDate": String,
    "sex": String,
    "gender": String,
    "phone": number,
    "adresse": String,
    "prsnlRoleIds": [number],
    "total": number,
    "selectedUserId":number,
    "ids":[], 
    "entities":{}
}

这就是我遵守诺言的方式:

return this.persnlService.getPersnl(data)
    .pipe(
      map((response) => response)
    ).subscribe((obj) => {
    for (const prsnl of Object.values(obj)[2]) {
      console.log('ids', prsnl.id);
      this.persnels = {
        id : prsnl.id,
        firstname: prsnl.id,
        lastname : prsnl.firstname,
        fullname: prsnl.fullname,
        profession: prsnl.function,
        dob: prsnl.dob,
        nationality: prsnl.nationality,
        createdDate: prsnl.createdDate,
        sex: prsnl.sex,
        gender: prsnl.gender,
        phone: prsnl.phone,
        adresse: prsnl.adresse,
        prsnlRoleIds: prsnl.prsnlRoleIds,
        total: 10,
        selectedUserId:0,
        ids:[] ,
        entities:{},
      };
    }; this.store.dispatch(loadPrsnls({this.persnels}));
  })

问题是 Visual Studio 在尝试使用 this.store.dispatch(loadPrsnls({this.persnels})) 发送 NgRx 存储中的数据时抱怨 {this.persnels}。它说:

Argument of type '{ this: any; }' is not assignable to parameter of
type '{ prsnls: prsnlStateInterface[]; }'.
   Object literal may only specify known properties, and 'this' does not exist in type '{ prsnls: prsnlStateInterface[]; }

截图如下:

我不明白的是,我没有定义 persnels 类型,而是 prsnlStateInterface 类型。此外,当我将 this.store.dispatch(loadPrsnls({this.persnels})) 替换为 console.log('persnl', this.persnels) 时,项目编译但在控制台中 prsnels 属性未定义。

我在这里遗漏了什么以及如何正确处理?

您必须将 this.prsnls 分配给 属性。 在不知道操作是如何键入的情况下,请尝试以下操作(或类似操作):

//                                assign the value to the `persnels` property
this.store.dispatch(loadPrsnls({ persnels: this.persnels}))