You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular添加新代码后如何刷新另一组件的下拉选项?

Angular添加新代码后刷新下拉列表问题解决

我刚接触Angular,现有CodeComponent组件包含下拉框与添加按钮,另有CodeNewComponent组件用于添加新代码的表单。希望添加新代码后重新加载下拉框中的代码列表,尝试用服务订阅的方式但未成功,相关代码如下:

CodeComponent代码

import { AfterViewInit, Component, OnInit, OnDestroy, ViewChild, numberAttribute } from '@angular/core';
import { CommonModule, NgFor } from '@angular/common';
import { CodeNewComponent } from './code-new/code-new.component';

import { FormsModule } from '@angular/forms';
import { IUITKSelectItemProps, UITKSelectModule, UITKTableDataSource, UITKTableModule } from '@uitk/angular';
import { CodeService } from './code.service';

import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { Subscription } from 'rxjs';
import { CommonService } from '../shared/common.service';

@Component({
  selector: 'app-code',
  standalone: true,
  imports: [CommonModule, NgFor, FormsModule, RouterModule, UITKSelectModule, CodeNewComponent],
  templateUrl: './code.component.html',
  styleUrl: './code.component.css'
})
export class CodeComponent implements OnInit, OnDestroy{
  messageReceived: any;
  private subscriptionName: Subscription = new Subscription();

  constructor(private _codeService: CodeService, 
    private _service: CommonService,
    private activatedRoute: ActivatedRoute, private router: Router)
  {    
    if(this.tableGroupCode === undefined){
      this.tableGroupCode = {id: '', label:'', value:''};
    }
    this.subscriptionName= this._service.getUpdate().subscribe
    (message => {
    this.messageReceived = message;
    if (message=='New Code added'){
        this.getCodes(); 
       }
    });
  }

  ngOnInit(): void {
    this.getCodes();
   }
   
   getCodes() : void
   {
    console.log('Calling this.GetCodes()');
    this._codeService.GetCodes().then(
      (codes) => {
       
          for(let entity of codes){
            this.codes.push({id: entity.Code, label: entity.Description, value: entity.Code});
          }
      },
  );
   }
   codes: IUITKSelectItemProps[] = [];
   tableGroupCode: IUITKSelectItemProps|undefined;;

   onSelect(groupCode: IUITKSelectItemProps|undefined){
    if(groupCode !== undefined && groupCode?.id!='')
      {
        localStorage.setItem('selectedTableGroupCode', groupCode?.id??"\"");
      }
   }

   ngOnDestroy() {
    this.subscriptionName.unsubscribe();
}
}

CodeNewComponent提交按钮代码

onSubmit() {
    const formValue = this.codeForm.getRawValue();
    this.newCode = new Code(
    'TableGroupCode',
    formValue.codeControl!,  
    formValue.descriptionControl!,
    'A'
    );

    this._codeService.InsertUpdateCode(this.newCode).then(
      (code) => {
          this.returnedCode = code;
      },
    );
    this.alertConfig.content = 'Table Group Code saved successfully!';
    this.alertService.setContainerConfig({position: 'top-right'});
    this.alertService.showNotification(this.alertConfig);
    this._service.sendUpdate('New Code added');    
    this.router.navigate(['/']);
   
  }

问题分析与修复方案

核心问题

你的实现方向正确,但存在3个关键问题导致刷新失败:

  1. getCodes()未清空旧数组,重复调用会导致数据累加
  2. 异步保存操作未完成就发送刷新通知,新代码可能还未写入数据库
  3. 路由跳转时机过早,可能导致CodeComponent未接收到通知就被销毁

修复步骤

1. 修复getCodes()方法,清空旧数据

每次获取新列表前清空codes数组,避免重复数据:

getCodes() : void
{
  console.log('Calling this.GetCodes()');
  this.codes = []; // 清空旧数组
  this._codeService.GetCodes().then(
    (codes) => {
        for(let entity of codes){
          this.codes.push({id: entity.Code, label: entity.Description, value: entity.Code});
        }
    },
  );
}

2. 确保保存完成后再发送通知

将刷新通知和路由跳转逻辑移到InsertUpdateCode的回调中,保证数据已成功写入:

onSubmit() {
  const formValue = this.codeForm.getRawValue();
  this.newCode = new Code(
    'TableGroupCode',
    formValue.codeControl!,  
    formValue.descriptionControl!,
    'A'
  );

  this._codeService.InsertUpdateCode(this.newCode).then(
    (code) => {
        this.returnedCode = code;
        // 数据保存成功后执行后续操作
        this.alertConfig.content = 'Table Group Code saved successfully!';
        this.alertService.setContainerConfig({position: 'top-right'});
        this.alertService.showNotification(this.alertConfig);
        this._service.sendUpdate('New Code added');    
        this.router.navigate(['/']);
    },
  );
}

3. 确认CommonService的Subject实现

确保你的CommonService使用正确的RxJS Subject实现消息传递:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class CommonService {
  private updateSubject = new Subject<string>();
  private update$ = this.updateSubject.asObservable();

  sendUpdate(message: string) {
    this.updateSubject.next(message);
  }

  getUpdate() {
    return this.update$;
  }
}

4. 可选:父子组件直接传值(若为父子关系)

如果CodeNewComponent是CodeComponent的子组件,可直接用@Output事件传递新数据,无需通过服务:

  • 在CodeNewComponent中定义输出:
    @Output() codeAdded = new EventEmitter<IUITKSelectItemProps>();
    
  • 在保存回调中发射事件:
    this.codeAdded.emit({
      id: formValue.codeControl!, 
      label: formValue.descriptionControl!, 
      value: formValue.codeControl!
    });
    
  • 在CodeComponent模板中监听事件:
    <app-code-new (codeAdded)="onCodeAdded($event)"></app-code-new>
    
  • 在CodeComponent中添加处理方法:
    onCodeAdded(newCode: IUITKSelectItemProps) {
      this.codes.push(newCode);
      // 或调用getCodes()刷新整个列表
    }
    

内容的提问来源于stack exchange,提问作者Naomi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 22:55:57