可以将静态数据传递给Angular 2路由而不在URL上显示。
但是如何以相同的方式传递动态数据/对象?
答案 0 :(得分:4)
您可以使用解析器。解析器返回的数据可用于路由配置上静态data
的路由
有关示例,请参阅https://angular.io/guide/router#resolve-guard
@Injectable() export class CrisisDetailResolve implements Resolve<Crisis> { constructor(private cs: CrisisService, private router: Router) {} resolve(route: ActivatedRouteSnapshot): Promise<Crisis>|boolean { let id = route.params['id']; return this.cs.getCrisis(id).then(crisis => { if (crisis) { return crisis; } else { // id not found this.router.navigate(['/crisis-center']); return false; } }); } }
path: '', component: CrisisListComponent, children: [ { path: ':id', component: CrisisDetailComponent, canDeactivate: [CanDeactivateGuard], resolve: { crisis: CrisisDetailResolve } },
ngOnInit() { this.route.data .subscribe((data: { crisis: Crisis }) => { this.editName = data.crisis.name; this.crisis = data.crisis; }); }
答案 1 :(得分:1)
你可以做两件事 1.不推荐但使用数据作为路由器参数并传递,
{ path: 'some:data', component: SomeComonent }
并用作
let data = {"key":"value"}
this.router.navigate(['/some', data)
2.而不是通过路径参数传递数据(因为数据可能很大并且也容易受到攻击,因为它可以被用户调整)
@Injectable()
export class SomeService {
data = {};
}
@Component({...
providers: [SomeService]
export class Parent {
constructor(private someService:SomeService) {}
private click() {
this.someService.data = {"key":"value"}
}
}
答案 2 :(得分:1)
最好结合以上两个答案:
/crisis/15
结尾的URL,它将把危机的全部数据传递给CrisisComponent。我们需要解析器,但是我认为OP不想在URL中显示任何数据。因此,解决方案是将共享数据放入Resolver本身:与组件不同,服务是长期存在的,并且始终只有一个实例,因此数据在resolver中是安全的:
// --- CrisisDetailResolve ---
// In the function body, add:
private currentCrisisId: number | string
set(crisisId: number | string) {
this.currentCrisisId = crisisId
}
// change line 5 of CrisisDetailResolve:
let id: number = 0 + this.currentCrisisId
// -- In your code --
// You can now navigate while hiding
// the crisis number from the user:
private click(crisisId : string | number) {
// tell resolver about the upcoming crisis:
this.crisisResolve.set(crisisId)
// navigate to CrisisDetail, via CrisisResolve:
this.router.navigate(['/crisisDetail')
// CrisisDetail can now receive id and name in its NgOnInit via `data`,
// as in Günter Zöchbauer's answer and the Angular docs
}
答案 3 :(得分:0)
您可以使用状态对象从Angular7.2中传递动态数据
在Component中,使用navigationByUrl发送任何数据
public product = { id:'1', name:"Angular"};
gotoDynamic() {
this.router.navigateByUrl('/dynamic', { state: this.product });
}
并使用history.state读取它
In dynamicComponent
ngOnInit() {
this.product=history.state;
}