創建一個服務來通知我的組件對“idCustomer”的任何更改。我想在該屬性更改時執行一些操作。這些動作必須在不同的組件中完成。我制作了一個 console.log 以了解是否收到了更改。但它只向我顯示了一個組件的訊息。我是 Angular 的新手,如果有更有效的方式來傳達“idCustomer”,那將是受歡迎的。Section 和 Customer 是兄弟姐妹。
登錄服務
idCustomerChanged = new Subject<string>();
constructor(private http: HttpClient) { }
login(requestBody: any): Observable<ResponseBody> {
return this.http.post<ResponseBody>(`${this.apiServerUrl}/Customer/GetCustomerLogin`, requestBody);
}
addIdCustomer(idCustomer: string) {
this.idCustomer = idCustomer;
this.idCustomerChanged.next(this.idCustomer);
}
removeIdCustomer() {
this.idCustomer = '';
this.idCustomerChanged.next(this.idCustomer);
}
getIdCustomer() {
return this.idCustomer;
}
LoginComponent(更改“idCustomer”)
submit() {
if (this.form.valid) {
this.loginService.login(this.form.value).subscribe((response) => {
if (response.data) {
this.loginService.addIdCustomer(response.data[0].idCustomer);
this.router.navigate(['/products']);
} else {
this.error = 'Invalid Credentials';
}
});
}
}
NavBarComponent(它顯示訊息)
idCustomer: string = '';
subscription: Subscription;
constructor(private loginService: LoginService, private router: Router) {
this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer ' from nav-bar');
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
CustomerComponent(這不是)
idCustomer: string = '';
submenusCustomer = ['Profile', 'History', 'Account Payables'];
subscription: Subscription;
constructor(private loginService: LoginService) {
this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer ' from customer-page');
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
SectionComponent(這不是)
idCustomer: string = '';
subscription: Subscription;
constructor(private loginService: LoginService) {
this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer ' from seccion-page');
});
}
ngOnInit(): void {
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
uj5u.com熱心網友回復:
最好將其他變數回傳主題添加為可觀察的:在您的登錄服務之上并在定義您的主題之后:
idCustomerChanged = BehaviorSubject<any>({})<string>();
//new
idCustomerChanged$:Observable = idCustomerChanged.asObservable();
//// 在您的 CustomerComponent 和其他組件上:
idCustomerChanged$:Observable;//declare your observable;
constructor(private loginService: LoginService) {
this.idCustomerChanged$ = this.loginService.idCustomerChanged$
this.subscription = this.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer ' from seccion-page');
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/472032.html
