【问题标题】:How to get the value from toPromise() in angular?如何从角度获取 toPromise() 的值?
【发布时间】:2019-05-07 21:05:13
【问题描述】:

我正在制作 Angular 应用程序,我正在其中进行服务调用,

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

异步 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...

【问题讨论】:

    标签: angular typescript angular5 angular6 angular-services


    【解决方案1】:

    要读取承诺值,请使用可链接的 .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));
           });
        });
    

    【讨论】:

    • 如果我等待,它给出了错误,因为我在 foreach 函数中进行了这个调用..请查看我编辑的问题..
    • 我已经更详细地更新了我的问题,在 foreach 里面有很多元素我只需要为element.elementType === 'dropdown' 执行此操作,所以在里面我尝试调用服务并将值存储到newValue变量.. 使用您的解决方案,我如何单独为element.elementType === 'dropdown' 实现它,而不需要离开 foreach.. 请帮我处理这种情况..
    • 您需要为 promise 和元素维护一个数组。最后,您需要将结果合并到问题数组中。
    • 那么在您编辑的解决方案中,变量newValue 将是什么。您已经给出了questionsPromiseResult.push(newValue);,但newValue 没有在任何地方声明值......
    • 还更新了我的问题async getQuestions(),使用正确的结束标签和返回值。请检查它。同时我会使用你的解决方案。
    【解决方案2】:

    我提供了一个示例,希望它能让您了解您想要什么:

    在您的服务文件中:

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

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2016-01-20
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多