我有一个应用程序,可以接收用户的数据并以表格形式对其进行验证。在这种情况下,当验证为true时,将启用按钮,并被允许用户提交其订单。
我不知道为什么我的科目不起作用。我的意思是我可以.next(value)
进入组件并投入使用,我可以console.log(value)
检查其是否投入使用。
我可以看到正在接收服务,但是该接收的值未在我要使用它们的组件中进行订阅。我停止运行项目,但无法修复。这是我尝试过的:
AuthService.ts
emailSubject=new Subject<string>();
getEmail(value)
{
console.log(value);
this.emailSubject.next(value); //prints email to the console correctly
}
CarService.ts
export class CarService
{
carrierSubject=new Subject<number>();
orderSubject=new Subject<Order[]>();
totalCostSubject=new Subject<number>();
lastTotalCostSubject=new Subject<number>();
getId(myIndex:number)
{
this.carrierSubject.next(myIndex);
}
setOrders(value)
{
console.log(value);
this.orderSubject.next(value);
}
setTotalCost(value)
{
this.totalCostSubject.next(value);
}
lastSetTotalCost(value)
{
this.lastTotalCostSubject.next(value);
}
CarPayment.ts
export class CarPaymentComponent implements OnInit {
car:Car;
selectedCar:string;
somePlaceholder : number = 0;
myArray:Order[];
email:string;
constructor(private carService:CarService,private authService:AuthService) { }
ngOnInit() {
this.carService.carrierSubject.subscribe(value=>
{
this.car=this.carService.getCar(value);
this.selectedCar=this.car.brand;
});
this.carService.lastTotalCostSubject.subscribe(value=>
{
this.somePlaceholder=value;
});
this.carService.orderSubject.subscribe(value=>
{
this.myArray=value;
}
);
this.authService.emailSubject.subscribe(value=>
{
this.email=value;
});
}
onSubmit()
{
console.log("ORDER INFO")
console.log('This order ordered by:'+this.email);
console.log("Ordered Car:"+this.selectedCar);
console.log("Ordered Parts:"+this.myArray);
console.log("Total Cost:"+this.somePlaceholder);
}
}
答案 0 :(得分:1)
正如@lealceldeiro和@FatemeFazli提到的那样,您需要使用BehaviorSubject
或ReplaySubject
。您的代码无法正常工作的原因是,您的可观察对象尚未触发任何值。本质上,当您执行.subscribe
时,您将陷入更改事件。但是就您而言,该更改尚未被触发。
AuthService.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs'; //<----Add this line
@Injectable()
export class AuthService {
emailSubject = new BehaviorSubject<string>("test@test.com"); //<--- provide an initial value here
getEmail(value) {
console.log(value);
this.emailSubject.next(value); //prints email to the console correctly
}
}
CarService.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class CarService {
carrierSubject = new BehaviorSubject<number>(0); //<-- provide an initial value here
orderSubject = new BehaviorSubject<Order[]>([]); //<-- provide an initial value here
totalCostSubject = new BehaviorSubject<number>(0); //<-- provide an initial value here
lastTotalCostSubject = new BehaviorSubject<number>(0); //<-- provide an initial value here
getId(myIndex: number) {
this.carrierSubject.next(myIndex);
}
setOrders(value) {
console.log(value);
this.orderSubject.next(value);
}
setTotalCost(value) {
this.totalCostSubject.next(value);
}
lastSetTotalCost(value) {
this.lastTotalCostSubject.next(value);
}
}