[英]How do I pass data from one component to another in Angular?
I am working on a quiz app with Angular.我正在使用 Angular 开发一个测验应用程序。 I need to get the value of correctAnswersCount in my ResultsComponent.
我需要在我的 ResultsComponent 中获取正确答案计数的值。 I'm getting the value of 0 for correctAnswersCount in ResultsComponent when I really need the value of the total correct answers at the end of the quiz, and also getting value of 1166 during the quiz in place of correctAnswersCount.
当我在测验结束时确实需要总正确答案的值时,我在 ResultsComponent 中得到了正确答案计数的值 0,并且在测验期间也得到了 1166 的值来代替正确答案计数。 I think the code looks correct, just the value that I'm getting is wrong.
我认为代码看起来是正确的,只是我得到的值是错误的。 Not sure what I'm doing wrong.
不知道我做错了什么。 This is my code:
这是我的代码:
in my QuizService:在我的测验服务中:
@Injectable({ providedIn: 'root' })
export class QuizService {
correctAnswersCountSubject = new BehaviorSubject<number>(0);
sendCountToResults(value) {
this.correctAnswersCountSubject.next(value);
}
}
in my DI-Quiz Component:在我的 DI 测验组件中:
ngOnInit() {
this.quizService.correctAnswersCountSubject.subscribe(data => {
this.count = data + 1;
});
this.sendCountToQuizService(this.count);
}
sendCountToQuizService(count) {
this.quizService.sendCountToResults(count);
}
and in my ResultsComponent:在我的 ResultsComponent 中:
constructor(private quizService: QuizService) {}
ngOnInit() {
this.quizService.correctAnswersCountSubject.subscribe(data => {
this.correctAnswersCount = data;
});
}
Please can you help.请你帮忙。 Thank you.
谢谢你。
I will give you some tips that my help.我会给你一些提示,我的帮助。
@Injectable({providedIn: 'root' })
on QuizService to guarantee a singleton instance of this service across the whole app.@Injectable({providedIn: 'root' })
来保证整个应用程序中此服务的 singleton 实例。this.sendCountToQuizService
inside the callback of the subscription.this.sendCountToQuizService
。 Edit:编辑:
I think you are somehow creating recursive events at DIQuizComponent by subscribing and sending new values to same Subject on the same place.我认为您在 DIQuizComponent 上通过订阅和发送新值到同一个地方的同一个主题以某种方式创建递归事件。 As correctAnswersCountSubject is a BehaviorSubject, you can get the value of correctAnswersCountSubject without subscribing to it using
getValue
method.由于 correctAnswersCountSubject 是一个 BehaviorSubject,因此您无需使用
getValue
方法订阅即可获取 correctAnswersCountSubject 的值。
This time i've created a demo on stackblitz , hope this helps.这次我在stackblitz上创建了一个演示,希望对您有所帮助。
Edited Again:再次编辑:
I've debugged your code and with some modifications I resolved all problems and they are:我已经调试了您的代码,并通过一些修改解决了所有问题,它们是:
QuizQuestionComponent
, add the decorator @Output() on answer EventEmitter.QuizQuestionComponent
中,在答案 EventEmitter 上添加装饰器 @Output()。DependencyInjectionQuizComponent
, on the nextQuestion method, this.answer is set as null before call the checkIfAnsweredCorrectly method who needs the answer value.DependencyInjectionQuizComponent
,在 nextQuestion 方法上, this.answer 设置为 null ,然后调用需要答案值的 checkIfAnsweredCorrectly 方法。DependencyInjectionQuizComponent
, you are not incrementing the this.count, I did it on the checkIfAnsweredCorrectly method.DependencyInjectionQuizComponent
,您没有增加 this.count,我是在 checkIfAnsweredCorrectly 方法上完成的。 Demo here: stackblitz在这里演示: stackblitz
If you want to pass data between components you have a couple of options.如果你想在组件之间传递数据,你有几个选择。 I'm not going to assume anything about your scenario and whether these will work, because in reality a lot of times when we are new, we realize that we need to slightly re-architect our components in order to achieve what we want, so instead, I will share the methods available to you.
我不会假设您的场景以及这些是否会起作用,因为实际上很多时候当我们是新手时,我们意识到我们需要稍微重新架构我们的组件才能实现我们想要的,所以相反,我将分享您可用的方法。
Standard Data Binding标准数据绑定
If you are trying to pass data from a parent component to a child component, you can simple bind the data when you add your component to the parent component.如果您尝试将数据从父组件传递到子组件,则可以在将组件添加到父组件时简单地绑定数据。
parent.component.html父组件.html
<child-component [myData]="myDataAsIsInParentComponent"></child-component>
child.component.ts child.component.ts
@Input() myData: <YourType>;
Emitting Data Upwards向上发射数据
If you are trying to pass data from a child component to a parent component, you can emit your values up the component tree (aka bubbling up the component tree)如果您尝试将数据从子组件传递到父组件,则可以将值发送到组件树(也就是冒泡组件树)
parent.componenent.html父组件.html
<child-component (myEmitter)="functionToCallInParent($event)"></child-component>
parent.component.ts父组件.ts
functionToCallInParent($event) {
const myPassedData = $event;
}
child.component.ts child.component.ts
@Output myEmitter: EventEmitter<myType> = new EventEmitter<myType>();
Now, those are baked in solutions that come out-of-the box with Angular.现在,这些已在 Angular 开箱即用的解决方案中得到解决。
State Management ie Redux, etc. State管理即Redux等
I highly suggest that you explore state management solutions like redux via NGRX if you want to have some truly awesome data storage and data passing powers.我强烈建议您通过 NGRX 探索 state 管理解决方案,例如 redux,如果您想拥有一些真正出色的数据存储和数据传递能力。
NGRX is amazing. NGRX 很棒。 It's a bit intimidating for some at first, but the benefits are insane?
一开始对一些人来说有点吓人,但好处是疯狂的? Imagine being in module x and needing data from module y and neither module is connected by a component, Well you wouldn't be able to to pass the data up and/or down the component tree in that scenario.
想象一下,在模块 x 中需要来自模块 y 的数据,而这两个模块都没有通过组件连接,那么在这种情况下,您将无法在组件树中向上和/或向下传递数据。 but you can with redux.
但你可以用 redux。
Hope this helps.希望这可以帮助。
Simple solution will be using service as store for storing correct answers count.简单的解决方案将使用服务作为存储正确答案计数的存储。 Please find below solution:
请找到以下解决方案:
In your service declare one private variable and write getters and setters for it in service as below:在您的服务中声明一个私有变量并在服务中为其编写 getter 和 setter,如下所示:
private correctAnswerCount:number;
//if you are calling this method for each correct answer
incrementCorrectAnswerCount(){
this.correctAnswerCount++;
}
//if you are calling this method once
setCorrectAnswerCount(value:number){
this.correctAnswerCount = value;
}
//you can fetch this method from any compononent so as the value of correctAnswerCount
getCorrectAnswerCount(){
return this.correctAnswerCount;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.