简体   繁体   English

路由之间的角度传递数据

[英]Angular Passing Data Between Routes

I have a little problem using routes in angular 4. You know, when I am trying to pass data from a component to another using navigate('root', data) , I just received [object Object],[object Object],[object Object] .我在 angular 4 中使用路由时遇到了一个小问题。你知道,当我尝试使用navigate('root', data)将数据从一个组件传递到另一个组件时,我刚收到[object Object],[object Object],[object Object]

Component组件

export class FillRequestComponent implements OnInit {

  constructor(private route: Router, private dataRoute: ActivatedRoute) { }

  ngOnInit() {
    const key: Products = this.dataRoute.snapshot.params['objectProducts'];
    console.log(key);
  }

Interface界面

export interface Products {

  color: string,
  question: string,
  surname: string,
  icon: string,
  selected: boolean,
  transparent: boolean
}

Send Method发送方法

const data = {
      category: this.optionSelected,
      objectProducts: this.optionSelected === 'CREDIT' ? this.productCreditList :
        this.productAccountsList
    };

    this.route.navigate(['/requests/fill', data]);

In the current version this is now available in @angular/router .在当前版本中,它现在可以在@angular/router

Angular 7.2 introduces route state to NavigationExtras , which takes an object literal similar to queryParams , etc. Angular 7.2NavigationExtras引入了路由状态,它采用类似于queryParams等的对象字面queryParams

The state can be set imperatively:可以强制设置状态:

this.router.navigate(['example'], { 
  state: { example: 'data' } 
});

or declaratively:或声明性地:

<a routerLink="/example" [state]="{ example: 'data' }">
  Hello World
</a>

And read in a top-level component using:并使用以下命令读入顶级组件

this.router.getCurrentNavigation().extras.state;

or within child components using:或在子组件中使用:

window.history.state

Added a working example of it being used on StackBlitz添加了一个在StackBlitz上使用的工作示例

When you pass an object as a route parameter, it causes to call toString on that object and you get the result [object Object] from the object.当您将一个对象作为路由参数传递时,它会导致对该对象调用toString并从该对象中获得结果[object Object]

 const obj = {}; console.log(obj.toString());

If you want to pass complex type, you need to stringify it to a string and pass as a string .如果你想通过复杂的类型,你需要stringify到一个string并传递一个string After when you get it, you need again to parse into an object.得到后,需要再次解析为对象。

this.route.navigate(['/requests/fill', JSON.stringify(data)]);

and access later并稍后访问

const key: Products = JSON.parse(this.dataRoute.snapshot.params['objectProducts']);

You can't pass list of data in params您不能在 params 中传递数据列表

So you need convert to string the list of objects then pass所以你需要将对象列表转换为字符串然后传递

navigate('root',   JSON.stringify(data))

Then do parsing while get this然后在得到这个的同时进行解析

const key: Products =JSON.parse(this.dataRoute.snapshot.params['objectProducts']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM