如何通过Angular路由导航传递对象作为数据。

huangapple go评论62阅读模式
英文:

How to pass an object as data throw angular router navigation

问题

这段代码中,我有一个路由,它从一个对象中获取一个id并导航到路由:

this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id])

这段代码可以正常工作,但我想要传递完整的数据对象到即将呈现的屏幕,该怎么做?

这个问题期望得到一个解决方案,以传递除了我用来导航到新路由的id之外的其他数据。

英文:

I have a route like that that get an id from an object and get the route:

this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id])

These work well but I want pass apart the complete object of data in the screen i will render calling the route how can i do that?

What that question a expecte get a solution to pass data appart from the id that i use to navigate to new route

答案1

得分: 2

通过路由传递数据对象并不是一个好的做法。我的建议是通过通用服务或BehaviorSubject(rxjs)来传递这样的数据。

顺便说一下,如果你想通过路由传递数据,可以按照以下方式进行:

在当前组件中,你需要像下面这样设置数据到路由中:

import { Component } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';

@Component({
  selector: 'app-form1',
  templateUrl: './form1.component.html',
  styleUrls: ['./form1.component.css']
})
export class Form1Component {
  
  constructor(private router: Router) {

  }

  handleButtonClick() {
    const myObject = { name: 'John', age: 30 };

    const navigationExtras: NavigationExtras = {
      state: {
        data: myObject
      }
    };

    this.router.navigate(['/list'], navigationExtras);
  }
}

然后你需要在目标组件的 ngOnInit 中访问这个数据:

ngOnInit() {
    const currentState = this.router.lastSuccessfulNavigation;
    console.log(currentState?.extras)
}
英文:

Passing data objects through routes is not a good practice. My suggestion is pass such data through the common service or BehaviorSubject(rxjs).

btw if you want to some how pass the data through routes here is the way

In current component you have to set the data to route like bellows

import { Component } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';

@Component({
  selector: 'app-form1',
  templateUrl: './form1.component.html',
  styleUrls: ['./form1.component.css']
})
export class Form1Component {
  
  constructor(private router: Router) {

  }

  handleButtonClick() {
    const myObject = { name: 'John', age: 30 };

    const navigationExtras: NavigationExtras = {
      state: {
        data: myObject
      }
    };

    this.router.navigate(['/list'], navigationExtras);
  }
}

Then you have to access the data inside the target component ngOnInit

ngOnInit() {
    const currentState = this.router.lastSuccessfulNavigation;
    console.log(currentState?.extras)

  }

huangapple
  • 本文由 发表于 2023年6月12日 15:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定