我有一个简单的组件结构,其中有一个名为 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/