Как получить значение из toPromise () в угловых? - PullRequest
0 голосов
/ 06 декабря 2018

Я делаю угловое приложение, в котором я делаю сервисный вызов как,

let newValue =  this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();

и console.log(newValue) дает,

{"__zone_symbol__state":null,"__zone_symbol__value":[]}

Здесь мне нужно сохранить значениеиз службы в переменную newValue.

При использовании toPromise.then.toPromise().then(function (result) { }) также я получаю тот же результат.

Пожалуйста, помогите мне сохранить значения службы с помощью toPromise() дляпеременная newValue ..

Редактировать:

Конструктор:

  constructor(private http: HttpClient, private dynamicService: NgiDynamicFormsService) {
    this.newArray = AppConfig.settings.template.templateFormJSON;
  }

Async getQuestions ()

          async  getQuestions() {

            let questions: any = [];

            this.newArray.forEach(element => {
          if (element.elementType === 'textbox') {
            questions.push(new TextboxQuestion(element));
          } else if (element.elementType === 'dropdown') {
                let newValue =  await this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();
    element.options = newValue;
    questions.push(new DropdownQuestion(element));
            } else if (element.elementType === 'textarea') {
            questions.push(new TextareaQuestion(element));
          } else if (element.elementType === 'checkbox') {
            questions.push(new CheckboxQuestion(element));
          }
            });
return questions.sort((a, b) => a.order - b.order);
  }

Здесь вы можете видеть, что после получения newValue мне нужно отправить значения из newValue в element.options .. А позже мне нужно позвонить questions.push(new DropdownQuestion(element)); для этого я не могу получить значение в newValue, и поэтому questions.push(new DropdownQuestion(element)) дает пустые значения, поэтому после сохранения значения в newValue мне нужно вызвать это значение, questions.push(new DropdownQuestion(element))

Мне нужно сделать этот вызов внутри forEach функции, поэтому, если я использую await , он выдаст ошибку IDE как,

[ts] 'await' expression is only allowed within an async function...

Ответы [ 2 ]

0 голосов
/ 06 декабря 2018

Я даю образец, надеюсь, он даст вам понимание того, что вы хотите:

в файле службы:

getTransactions(): Promise<{any}> {
  return this.http.get(`${Api.Url}transaction`).toPromise()
    .then(r => {
      return r;
    }).catch(error => {
      return Promise.reject(error);
    });
}

и в ваших component.ts, где вы хотите использоватьэтот сервис и получить данные:

this.transactionService.getTransactions().then(
        r => {
            console.log(r);
        }
    ).catch( e => {
        alert('error fetching data');
    });
0 голосов
/ 06 декабря 2018

Чтобы прочитать значение обещания, используйте цепной оператор .then.

let newValue =  this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();

newValue.then((value)=>console.log(value));

Вы также можете использовать aynsc / await

async func(){
   let newValue =  await this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();
}

---- Promise.all ----

async  getQuestions() {

    let questions: any = [];
    let questionsPromise: any = [];
    let questionsPromiseResult: any = [];
    this.newArray.forEach(element => {
       if (element.elementType === 'textbox') {
          questions.push(new TextboxQuestion(element));
       } else if (element.elementType === 'dropdown') {
        questionsPromise.push( this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise());
        questionsPromiseResult.push(element);
      } else if (element.elementType === 'textarea') {
        questions.push(new TextareaQuestion(element));
      } else if (element.elementType === 'checkbox') {
        questions.push(new CheckboxQuestion(element));
      }
    });

    Promise.all(questionsPromise).then(results =>{
       results.forEach(item,index=>{
          let element = this.questionsPromiseResult[index];
          element.options = item;
          questions.push(new DropdownQuestion(element));
       });
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...