angular - 如何在 ngOnInit 中使用 await/async?

标签 angular typescript ecmascript-6

我正在尝试调用 ngOnInit() 中的函数并为其提供两个值。所以这是我试图在 ngOnInit 中调用的函数: this.complexWordIdentification(this.postIWant, this.theHardWords);

这里的问题是 this.postIWantthis.theHardWords 正在 ngOnInit 本身中得到解决,如下所示,导致错误。现在我如何调用 this.complexWordIdentification(this.postIWant, this.theHardWords); 并在不出错的情况下向其提供这些值?

我一直在考虑 await 函数?但是我想不通,请问有什么建议吗?

这是我的ngOnInit:

ngOnInit() {
    this.isLoading = true;
    this.wordsLoaded = false;
    this.postLoaded = false;
    this.form = new FormGroup({
      annotation: new FormControl(null, {
        validators: [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(250)
        ]
      })
    });
    this.id = this.route.snapshot.paramMap.get('postId');
    this.annotationService.getWords();
    this.annotationSub = this.annotationService
      .getWordUpdateListener()
      .subscribe((thewords: ComplexWord[]) => {
        this.thewords = thewords;
        this.thewords.map(word => {
          this.theHardWords.push(word.word);
          this.wordWithAnnotation.push(word);
        });
        this.wordsLoaded = true;
        this.isLoading = this.postLoaded && this.wordsLoaded;
      });
    this.postsService.getPosts();
    this.postsSub = this.postsService
      .getPostUpdateListener()
      .subscribe((posts: Post[]) => {
        this.posts = posts;
        this.posts.map(post => {
          if (post.id === this.id) {
            this.postIWant = post.fileText;
          }
        });
        this.postLoaded = true;
        this.isLoading = !(this.postLoaded && this.wordsLoaded);
      });
    this.role = this.authService.getUserRole();
    this.userIsAuthenticated = this.authService.getIsAuth();
    this.authStatus = this.authService
      .getAuthStatus()
      .subscribe(isAuthenticated => {
        this.userIsAuthenticated = isAuthenticated;
        this.role = this.authService.getUserRole();
      });
}

如果有人能给我指出正确的方向,那就太好了,因为我在这个领域的经验还不够丰富。目前我不得不在 ngOnInit 之外调用 this.complexWordIdentification(this.postIWant, this.theHardWords); 以避免错误,但显然,我想调用它自动。

最佳答案

forkJoin 将两个订阅合并为一个订阅并返回它们的结果数组。当您在完成加载组件之前需要来自多个来源的数据时,在 ngOnInit 中使用它非常有用。

https://www.learnrxjs.io/operators/combination/forkjoin.html

import { Observable } from "rxjs/Observable";
    Observable.forkJoin(
        this.annotationService.getWordUpdateListener(),
        this.postsService.getPostUpdateListener()
    ).subscribe((data) => {
         // data[0] result from getWordUpdateListener
         this.thewords = data[0];
            this.thewords.map(word => {
              this.theHardWords.push(word.word);
              this.wordWithAnnotation.push(word);
            });
            this.wordsLoaded = true;

         // data[1] result from getPostUpdateListener
         this.posts.map(post => {
              if (post.id === this.id) {
                this.postIWant = post.fileText;
              }
            });
            this.postLoaded = true;
        this.isLoading = false;
        this.complexWordIdentification(this.postIWant, this.theHardWords);
    }, (err) => {
        // error handling
    });

编辑:在 RXJS 5 及以下版本中添加了 Observable 的导入语句

编辑:RXJS 6 更新,更改导入语句

import { forkJoin} from 'rxjs';
forkJoin(this.annotationService.getWordUpdateListener(),
            this.postsService.getPostUpdateListener()
).subscribe((data) => { \\do stuff}, (err) => { \\ do error stuff}

编辑 2:RXJS 更改了 forkJoin 的签名,它现在接受一个数组

    forkJoin([this.annotationService.getWordUpdateListener(),
            this.postsService.getPostUpdateListener()]
).subscribe((data) => { \\do stuff}, (err) => { \\ do error stuff}

关于angular - 如何在 ngOnInit 中使用 await/async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407261/

相关文章:

angular - 将按钮添加到 mat-tab-group

angular - 在 Angular 4 项目的功能性 e2e Protractor 测试中模拟休息调用

node.js - 如何在 Node.js 中注册全局 TypeScript Enum

javascript - 使用强类型 map

angular - 当自定义验证器返回错误对象时,formGroup.hasError 不返回 true 的问题

node.js - 如何在npm start上将scss编译为css

c# - 上传文件报错 415 Unsupported Media Type

访问对象文字的属性时出现 TypeScript 错误

node.js - Typescript 中的 out 目录具有相同的目录结构,怎么样?

javascript - 提高使用解构和递归处理数组的函数的性能