javascript - 在 Angular 6 中使用 Observable 的问题

标签 javascript angular observable angular6

我有一个简单的组件结构,其中有一个名为 gameplay 的 Angular 组件,其中有一个名为 question-box 的子组件。目标是通过游戏中的后端服务获取一个简单的字符串(效果很好),并将该字符串传递给 question-box要显示(这不起作用)。

这是我的代码:

gameplay.component.ts:

import { Component, OnInit, OnChanges } from '@angular/core';
import { QuestionsService } from '../services/questions.service';

@Component({
  selector: 'app-gameplay',
  templateUrl: './gameplay.component.html',
  styleUrls: ['./gameplay.component.css'],
})
export class GameplayComponent implements OnInit {

  constructor(private qService: QuestionsService) {

  }

  currentQuestion: string;

  ngOnInit() {
    this.qService.getQuestions().subscribe({
      next(data) {
        this.currentQuestion = data[0].question;
        console.log(this.currentQuestion); //logs correctly
      },
      complete() { console.log('Done')},
      error() { console.log('Error')},

    })
  }
}

gameplay.component.html:

<app-question-box [question]="currentQuestion"></app-question-box>

question-box.component.ts

 import { Component, OnInit, Input, OnChanges, SimpleChange } from '@angular/core';

@Component({
  selector: 'app-question-box',
  templateUrl: './question-box.component.html',
  styleUrls: ['./question-box.component.css']
})
export class QuestionBoxComponent implements OnInit {

  @Input() question: string;

  constructor() {
  }

  ngOnInit() {
  }
}

question-box.component.html

<mat-card md-colors="{background: 'orange'}">
  <mat-card-content>
    <p>{{question}} </p>
  </mat-card-content>

</mat-card>

我尝试在模板中使用异步管道,但它不起作用。 我希望看到 next() 中得到的字符串在 child 的<p> ;但我什么也没看到。但是,该字符串会正确记录在控制台上。

如有任何帮助,我们将不胜感激。如果我遗漏了寻找解决方案所需的一些信息,请告诉我。谢谢。

最佳答案

根据我的评论:

如果您以这种方式传递回调,则回调中的 this 是函数,而不是组件本身。

更改为箭头函数即可解决问题:

this.qService.getQuestions().subscribe(
      data => this.currentQuestion = data[0].question,
      error => console.log('Error'),
      () => console.log('Done')
);

关于javascript - 在 Angular 6 中使用 Observable 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52604778/

相关文章:

java - Angular2 - 下载从 RestService 收到的 XLS

javascript - 从组件的 OnInit 调用时,Angular 2 路由器无法导航

javascript - Knockout js 绑定(bind)未更新

javascript - 按预期顺序对字符串进行排序

javascript - 具有 apache 别名的已用服务人员无法正常工作

angular - 如何以 Angular 获取计算机中所有打印机的列表

angular - 将HttpHandler返回的Observable与HttpInterceptor中的另一个合并(Angular 8)

angular - 链接多个 RxJS Observable 运算符的问题

javascript - Google+ API 与 youtube-api-v3

javascript - 如何强制将链接另存为,下载链接,而不是忽略事件的服务人员?