方法调用完成后可观察到的返回值

时间:2019-12-24 11:57:16

标签: angular rxjs rxjs-observables

getModel()方法始终返回带有空名称数组的数组,即使当Observable语言返回值时也是如此。为什么?

    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;
  }

1 个答案:

答案 0 :(得分: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;
});

}