【问题标题】:Navigating edit window right after create a value in Angular 2+在Angular 2+中创建值后立即导航编辑窗口
【发布时间】:2019-01-03 13:30:12
【问题描述】:

我有一个正在尝试学习 Angular 的测试项目。在这个项目中,我有 2 个 HTML 表单,可让我创建参与者。基本上,为了简单起见,我将这些表单分为 2 个子表单。我使用第一个表单来捕获一些人口统计数据,并使用第二个表单添加更多详细信息,例如收入、教育详细信息等。我的方法如下:首先创建参与者,使用 routerActivatedRoute 导航第二个通过传递新创建的参与者 ID 和更新来形成。

基本上,第一个表单用于创建,第二个表单仅用于更新目的。如果我将任何数字作为参与者 ID,这两种形式都可以正常工作。但是,我无法在创建新参与者后立即将参与者 ID 传递给第二个表单。我得到undefined 而不是参与者ID。我不确定如何在创建后立即传递此参与者 ID,以便我可以使用该 ID 并更新其他详细信息。

这里是创建和更新 TypeScript 代码。请注意,我没有将服务和解析器代码放在这里,因为它们可以正常工作。唯一的问题是传递 id。

对于创建(第一种形式):

this.participantService.add(this.participant).subscribe(res => {
      console.log('participant has been created!');
    });
this.router.navigate(['public-access/form2/' + this.participant.id]);

和更新(第二种形式):

export class Form2Component implements OnInit {
  participant: any = {};

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private participantService: ParticipantService
  ) {
    route.params.subscribe(p => {
      this.participant.id = +p['id'] || 0;
    });
  }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.participant = data['participant'];
    });
  }

  submit() {
    // participant Update
    this.participantService.update(this.participant).subscribe(participant =>{
      this.participant = participant;
      this.router.navigate(['/public-access/form-success']);
      console.log('Participant study status is succefully saved!');
    }, error => {
      console.log('Participant study status is NOT saved!');
    });
  }

}

我收到的控制台中的实际错误是

zone.js:2969 GET http://localhost:5000/api/Participants/undefined 404(未找到)

实现这一目标的最佳方法是什么?任何帮助将不胜感激。

【问题讨论】:

  • 在收到add 函数的响应之前,您是否有可用的id
  • id 是自动生成的。就我而言,它是自动递增的唯一 int 值,因为我在后端使用 SQL 服务器。
  • 正确,但在您得到this.participantService.add 函数的响应之前是否可用?我最好的猜测是,您在subscribe 回调中获得了id
  • idad 函数之前如何可用?

标签: angular routes angular-routing angular-router


【解决方案1】:

您甚至在从后端获得id 之前就调用了navigate 函数。

您可能可以做的是,等待来自后端的响应并从那里获取id,然后导航。

对于创建(第一种形式):

this.participantService.add(this.participant).subscribe(res => {
  console.log('participant has been created!');

  // search for the id in your response object and append that
  this.router.navigate(['public-access/form2/' + <id>]);
});

【讨论】:

  • 你是对的。 router 无法获取 id,因为它不在订阅方法中。
  • 很高兴它有帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
相关资源
最近更新 更多