-2

getModel() method always return array with empty name array even when languages Observable returns value. why?

    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;
  }
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212
  • 2
    Does this answer your question? [How to return value from function which has Observable subscription inside?](https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside) – C.OG Dec 24 '19 at 12:03
  • ```return model;``` executes before subscribe so it is empty, return it in subscribe. – Fateme Fazli Dec 24 '19 at 12:04
  • i solved it using promise sir. – Saurabh Kumar Dec 24 '19 at 15:01

1 Answers1

2

You assign model.name outside of the subscribe. This will be executed before the code within the subscribe. Try this:

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

}

Lotte Lemmens
  • 551
  • 5
  • 11