【问题标题】:Use variable outside of promise block in Angular在 Angular 中使用 promise 块之外的变量
【发布时间】:2019-09-04 06:15:01
【问题描述】:

如何在 Angular 6 的组件中获取 promise 块之外的变量?

例如

    items:string[]=[];

    ngOnInit{

    const url='SOME URL';
    const promise = this.apiService.post(url);

        //Response
        promise.then(response => {
      this.items.push('abc');
      this.items.push('def');
        });

    this.items.forEach(item=>{
     alert(item);
    });

      }

我希望应用程序提醒 items 数组的内容

【问题讨论】:

标签: angular typescript promise angular6


【解决方案1】:

当你这样做时

this.items.forEach(item=>{
     alert(item);
    });

items 数组为空。

你需要把这段代码放进去

  promise.then(response => {
          this.items.push('abc');
          this.items.push('def');
         this.items.forEach(item=>{
            alert(item);
           });
     });

或者你可以使用 Observables 知道 Promise 何时结束并执行 foreach,你需要做这样的事情:

private subjectItems = new Subject<any>();

ngOnInit{

    this.subjectItems.asObservable().subscribe(o => {
        this.items.forEach(item=>{
         alert(item);
        });
      });

    const url='SOME URL';
    const promise = this.apiService.post(url);

        //Response
        promise.then(response => {
           this.items.push('abc');
           this.items.push('def');

           this.subjectItems.next(this.items)
        });
      }

【讨论】:

  • 问题是我希望应用程序在 promise 块之外提醒项目,因为我想在 promise 块之外使用 items 变量
  • 你必须有某种方式知道承诺已经解决。在.then 之后将警报放在块内的原因是你知道你的承诺已经解决了。否则,您可能会在承诺尚未解决时执行thisitems.forEach(item =&gt; alert(item)),因此由于列表为空,因此不会显示任何内容。如果您尝试在模板中使用this.items,则应该没问题,因为无论如何它都会在值更改时更新。
  • @freelancer86 我编辑我的答案以添加其他方法,使用 observables。
【解决方案2】:

这似乎是一个异步问题,我的意思是在您从服务获取数据之前显示您的警报,因此可以选择使用 Observablessubscribe。它应该等到获取数据后再使用它。

你也可以尝试在medium article之后使用async/await

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多