-2

即使语言 Observable 返回值,getModel() 方法也总是返回具有空名称数组的数组。为什么?

    export interface Category extends BaseModel {
      code: string;
      name: LocalizedValue[];
      description: LocalizedValue[];
      active: boolean;
    }

    getAllLanguages(): Observable<Language[]> {
       // this return list of languages
    }

    protected getModel(): Category {
    let model: Category = {
      id: '',
      code: '',
      name: [],
      description: [],
      active: false,
    };
    let nameField: LocalizedValue[] = [];
    this.languageService.getAllLanguages().subscribe(list => {
      list.forEach(l => {
        let n: LocalizedValue = {
          language: l.code,
          value: '',
        };
        nameField.push(n);
      });
    });
    model.name = nameField;
    return model;
  }
4

1 回答 1

2

您在订阅之外分配 model.name 。这将在订阅中的代码之前执行。尝试这个:

protected getModel(): Category {
let model: Category = {
  id: '',
  code: '',
  name: [],
  description: [],
  active: false,
};
let nameField: LocalizedValue[] = [];
this.languageService.getAllLanguages().subscribe(list => {
  list.forEach(l => {
    let n: LocalizedValue = {
      language: l.code,
      value: '',
    };
    nameField.push(n);
  });
  model.name = nameField;
  return model;
});

}

于 2019-12-24T12:02:26.477 回答