英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论