gpt4 book ai didi

javascript - 如何与 Angular 8 中的其他组件通信以添加总计

转载 作者:行者123 更新时间:2023-12-02 22:19:30 25 4
gpt4 key购买 nike

我是 Typescript 新手,我正在创建成本计算器应用程序。我有 8 个问题作为单独的组件和总成本组件。每个问题有 3 个不同的选项可供选择。选择选项后,我希望总成本随着用户在问题中的进展而累加。一旦用户回答了最终问题,我就会总结向他展示总成本。

我做了研究并找到了不同的答案,但似乎没有一个对我有用。大部分答案都是JS的。

我尝试使用rxjs/BehaviorSubject库但出现错误。这是我的代码。

totalCost.component.ts

import { Component, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';

@Component({
selector: 'totalcost',
template: `<div>
<p>Total: {{totalCost}}
</div>`

})

@Injectable({
providedIn: 'root'
})
export class TotalCost {


private totalCost = new BehaviorSubject<number>(0);
currentCost = this.totalCost.asObservable();

constructor(){

}

addCost(add: number){
this.totalCost.next(add);
console.log('addCost');
return this.totalCost;
}



}

这是第一个问题组成部分:

import { Component, OnInit, Injectable } from '@angular/core';
import { TotalCost } from '../totalCost/totalCost.component';

@Injectable({
providedIn: 'root'
})
@Component({
selector: 'first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.scss']
})



export class First {

totalCost: number;


constructor(private cost: TotalCost){

}

ngOnIt(){
this.cost.currentCost.subscribe(totalCost => this.totalCost = totalCost )
}

addToCost(value: number){
this.cost.addCost(value);
console.log('addToCost()');
}

}

这是第一个问题的 HTML:

<div class="container-fluid text-center">
<div>
<h3>Choose The Type Of Website</h3>
<input type="range" value="1000" id="budget">
<p>
<span>
<a [routerLink]="'/second'" (click)="addToCost(1000)"><img src="" alt="static"></a>
</span>
<span>
<a [routerLink]="'/second'" ><img src="" alt="Dynamic"></a>
</span>
<span>
<a [routerLink]="'/second'" ><img src="" alt="E-Commerce"></a>
</span>
</p>
</div>
</div>

当用户选择其中一个选项时,我希望总成本相加,直到用户到达最后一个问题。

这就是我的应用程序的样子

enter image description here

最佳答案

你可以这样尝试。
创建一项包含您的主题的公共(public)服务。

common.service.ts

@Injectable({
providedIn: 'root'
})
export class CommonService {
private totalCost = new BehaviorSubject<number>(0);

sendMessage(data: any) {
this.totalCost.next(data);
}
getMessage(): Observable<any> {
return this.totalCost.asObservable()
}
}

ComponentA//要发送数据的组件

export class ComponentA {
// here we are adding our common service which contain our subject
constructor(private brodcaster: CommonService){}

sendData(data) {
this.brodcaster.sendMessage(data);
}

ComponentB//要访问数据的组件

export class ComponentA {
// here we are adding our common service which contain our subject
constructor(private brodcaster: CommonService){
this.brodcaster.getMessage().subscribe(response => {
console.log(response);
})
}

关于javascript - 如何与 Angular 8 中的其他组件通信以添加总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com