Angular跨组件无法获取最新发射值的问题求助
解决Angular组件间npciUserName值同步问题
我尝试在app-bene-verification.ts组件中获取app-confirm-bottom-sheet组件内npciUserName变量的最新更新值,但始终无法成功。当前npciUserName一直被设置为默认值,app-confirm-bottom-sheet.html输入框中的最新值无法同步到app-bene-verification.ts中。
相关代码
app-confirm-bottom-sheet.ts
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core'; import { MatBottomSheet, MAT_BOTTOM_SHEET_DATA } from '@angular/material/bottom-sheet'; import { UtilityService } from '../../services/utility.service'; @Component({ selector: 'app-confirm-bottom-sheet', templateUrl: './confirm-bottom-sheet.component.html', styleUrls: ['./confirm-bottom-sheet.component.scss'] }) export class ConfirmBottomSheetComponent implements OnInit { sheetData: any; confirmForm!: FormGroup; npciUserName:any='' constructor( private bottomSheet: MatBottomSheet, @Inject(MAT_BOTTOM_SHEET_DATA) public data: any = {}, private fb: FormBuilder, private changeDetector: ChangeDetectorRef, private utilityService: UtilityService ) { } ngOnInit(): void { } updateUserName(): void { this.utilityService.updateNpciUserName(this.npciUserName); } checkNpci() { console.log(this.npciUserName); } }
app-confirm-bottom-sheet.html
<input type="text" [(ngModel)]="npciUserName" placeholder="Enter your name" (keyup)="updateUserName()">
app-bene-verification.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms'; import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { DatePipe } from '@angular/common'; import { MatBottomSheet } from '@angular/material/bottom-sheet'; import { ConfirmBottomSheetComponent } from './../../../../common/dialogs/confirm-bottom-sheet/confirm-bottom-sheet.component'; import { BankValidationService } from '../../services/bank-validation.service'; import { UtilityService } from './../../../../common/services/utility.service'; import { ExportService } from './../../../../common/services/export.service'; import { Subscription } from 'rxjs'; export interface BeneData { agent_ref_id: string agent_mobile_no: string account_holder_name: string account_number: string ifsc_code: string bank_name: string account_validation_status_refid: string bank_id: number retailer_name: string } @Component({ selector: 'app-bene-verification', templateUrl: './bene-verification.component.html', styleUrls: ['./bene-verification.component.scss'] }) export class BeneVerificationComponent implements OnInit { npciUserName: any = ''; npciUserNameSubscription!: Subscription; constructor(private bankValidationService: BankValidationService, private datePipe: DatePipe, private bottomSheet: MatBottomSheet, public utilityService: UtilityService, private exportService: ExportService, private fb: FormBuilder ) { this.range = new FormGroup({ fromDate: new FormControl(), toDate: new FormControl() }); this.npciUserName = 'Default Value'; } queryParams: any; nbtFormGroup!: FormGroup; ngOnInit(): void { this.npciUserNameSubscription = this.utilityService.npciUserName$.subscribe({ next: (value: any) => { if (this.npciUserName === '' || this.npciUserName === null) { this.npciUserName = value; } }, error: (error: any) => { console.error('Error fetching npciUserName:', error); this.npciUserName = 'Default Value'; // or handle the error in another way } }); this.queryParams = JSON.parse(sessionStorage.getItem('queryParams') as any); this.fromDate.setValue(new Date()); this.toDate.setValue(new Date()); this.getBeneDetails(this.fromDate.value, this.toDate.value); this.getReasonsList() } }
utility-service.ts
import { Injectable } from '@angular/core'; import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UtilityService { constructor(private _snackBar: MatSnackBar) { } private npciUserNameSubject = new BehaviorSubject<any>(null); npciUserName$ = this.npciUserNameSubject.asObservable(); updateNpciUserName(value: any) { this.npciUserNameSubject.next(value); } }
解决方法
1. 修正订阅逻辑的条件判断
在app-bene-verification.ts的订阅回调中,原代码限制只有this.npciUserName为空或null时才更新值,但初始化时已将其设为'Default Value',导致后续更新无法触发赋值。直接调整条件:
this.npciUserNameSubscription = this.utilityService.npciUserName$.subscribe({ next: (value: any) => { // 只要新值有效就更新 if (value !== null && value !== undefined) { this.npciUserName = value; } }, error: (error: any) => { console.error('Error fetching npciUserName:', error); this.npciUserName = 'Default Value'; } });
2. 确保导入FormsModule
使用[(ngModel)]双向绑定必须在组件所属的NgModule中导入FormsModule,否则双向绑定不生效:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // 其他导入项 FormsModule ], declarations: [ // 包含ConfirmBottomSheetComponent等相关组件 ] }) export class YourModule { }
3. 优化值的发射时机
将(keyup)事件替换为(input),确保输入框内容变化时立即触发更新:
<input type="text" [(ngModel)]="npciUserName" placeholder="Enter your name" (input)="updateUserName()">
4. 组件销毁时取消订阅
为避免内存泄漏,在app-bene-verification.ts中实现OnDestroy接口并取消订阅:
import { Component, OnInit, OnDestroy } from '@angular/core'; // ...其他导入项 export class BeneVerificationComponent implements OnInit, OnDestroy { // ...现有代码 ngOnDestroy(): void { this.npciUserNameSubscription.unsubscribe(); } }
内容的提问来源于stack exchange,提问作者Coder_7
相关产品推荐
相关产品推荐

