角度路由器。保持子级、事件用户输入之间的状态

问题描述 投票:0回答:1

我正在使用 Angular 16。我有一个父组件:

ComponentA
,路线为
'/parent-component/:customId'
ComponentA
有两条子路线:
ChildComponent1
与路线
'/child1'
ChildComponent2
与路线
'/child2'

ComponentA
有两个链路和路由器出口,如下:

<a routerLink="child1">Child1</a>
<a routerLink="child2">Child2</a>
<router-outlet></router-outlet>

ChildComponent1
首先调用API,然后创建动态表单。

当用户导航到

child1
,填写表单并转到
child2
并返回
child1
时,
child1
再次加载所有内容(调用API并重新创建动态表单),用户丢失了他的工作。所以我想保留用户输入,并且不想再次调用并创建动态表单。

有没有办法保持

child1
状态,甚至用户在表单条目中写入的内容?

angular angular-reactive-forms angular-router angular-state-managmement
1个回答
0
投票

由于您使用的是 router-outlet,因此无法使用父组件来保留状态,但无论如何最好使用共享服务内的行为主体来管理兄弟组件之间的状态

所以服务文件就像这样


export class CompAService {
  private formState$: BehaviorSubject<YourFormInterface | undefined> = new BehaviorSubject(undefined);

  constructor() { }

  getFormState() : Observable<YourFormInterface> {
    return this.formState$.asObservable()
  }
  
  updateFormState(state:YourFormInterface): void {
     this.formState$.next(state)
  }
}

在 Component1 ts 文件中,每次组件加载到视图中时,您都会订阅获取表单状态,如果组件第一次加载,您将在订阅中收到“未定义”,并且您可以调用 API 来获取任何数据你需要你声明


@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...']
})
export class Child1Component {
  form: FormGroup = new FormGroup() // your form group

  constructor(private compAService:CompAService, private destroyRef:DestroyRef){}

  ngOnInit():void{
    this.compAService.getFormState().pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe(state=>{
       if (!state) {
         this.setFormState()
       }else {
         this.form.patchValue(...state) // set all your values to the form 
       }
    })
  }

  setFormState():void {
    // on receiving your response from api call OR receiving values from your 
    // html form, set the state so you get it the next time
    this.compAService.updateFormState(state)
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.