【问题标题】:Error in StackBlitz: 'Unexpected strict mode reserved word' trying to use async/await with subscription.toPromise()StackBlitz 中的错误:“意外的严格模式保留字”尝试将 async/await 与 subscription.toPromise() 一起使用
【发布时间】:2020-05-07 01:03:42
【问题描述】:

我在 StackBlitz here 上设置了 Angular webapp 的一部分。

在其中,我正在尝试使用来自具有过滤、分页和排序功能的 firebase 的数据来实现 mat-table 的最佳方法。

最终编写了一个实现 MatTableDataSource 接口的类,名为 VideoDataSource in './videoDataSource.model.ts'。其中,有一个名为loadMatches() 的方法。这是一个async 方法:

async loadMatches(): Promise<any>{
    console.log("loadMatches entered");
    let results = await this.dbService.getMatchesV2().toPromise();
    console.log("results in loadMatches");
    console.log(results);
    let dbMatches = results.map(Match.fromJson);
    return dbMatches.toPromise();
  }

其中dbService.getMatchesV2() 又来自注入服务,如下所示:

getMatchesV2(){
    return this.db.list<Match>('/matches').valueChanges();
  }

其中 db 是 AngularFireDatabase 类型的数据库服务的参数。

app.component.ts 中的loadMatches() 调用如下所示:

this.data = await this.dataSource.loadMatches();

其中 data 是 AppComponent 的参数,类型为 Match[]

我收到错误“意外的严格模式保留字”,引用了没有任何意义的行号(在 app.module.ts 中;我想这是编译后的行号?) .问题在我尝试实现 async/await 后立即开始。 DatabaseService 主要处理 Observables,但我认为.toPromise() 足以解决问题。关于发生了什么的任何见解?非常感谢!

【问题讨论】:

  • 您可以删除 'use strict;'在您的 app.js 中作为快速修复。
  • 模型和服务文件有很多语法错误,甚至有一个接口没有正确实现,请全部修复并删除不必要的代码
  • 谢谢,@Reza!我发现了你提到的一些错误,现在正在努力改进它们。其中一些与我无法将 ES2017 添加到 compilerOptions 的事实有关,因为 AFAIK stack blitz 仍然不支持 tsconfig ?

标签: angular async-await angular-material stackblitz


【解决方案1】:

发生了什么?

保留关键字错误是由您的内部依赖项之一引发的。

具体在哪里?

app.component.ts,你有这行 -

this.data = await this.dataSource.loadMatches();

解决方法是什么?

async ngOnInit() {

为什么?!

由于您使用的是await,因此您在其中使用await 的函数需要标记为async。 await 表达式只允许在 async 函数中使用。在您的情况下,它是ngOnInit。 (记得在其他地方也这样做)。你可以在Typescript 1.7's release notes阅读更多内容

一般如何调试这些问题?

这是问题不在您实际寻找的地方的情况之一。因此,对 linter 错误进行常规检查(所有的 linter 错误!),并在不同的浏览器中尝试会有所帮助。您可能会在不同的浏览器中得到不同的错误和堆栈跟踪。

好的!好的!但是错误会消失吗?有用吗?

给你 - https://stackblitz.com/edit/angular-tmgbw7?file=src%2Fapp%2Fapp.component.ts

【讨论】:

  • 好眼光!谢谢你的收获,@Vandesh。现在完全有道理。我什至不再认为 ngOnInit() 是一种方法,哈哈。
猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 2020-11-09
  • 2020-04-28
  • 1970-01-01
  • 2018-03-27
  • 2015-04-09
  • 2017-11-03
  • 1970-01-01
相关资源
最近更新 更多