在路由器导航期间传递对象

时间:2016-06-30 13:09:51

标签: typescript angular angular2-routing

我想在路由器导航到目标组件期间传递对象。 目前我正在使用routeParams并将我的对象字符串化为字符串。这种方法有效,但我不喜欢这种解决方案。一个更好的解决方案怎么样?

export class Overview {
    //import {Router} from "@angular/router-deprecated";
    constructor(private router:Router) {}
    goToElementComponent(elem:Element) {
        this.router.navigate(['ElementDetail', {elem: JSON.stringify(elem)}]);
    }
}
export class ElementDetail {
    // import {RouteParams, Router} from "@angular/router-deprecated";
    this.elem : Element;

    constructor(private routeParams:RouteParams) {}

    ngOnInit() {
        var elem = JSON.parse(this.routeParams.get("elem"));
        if (elem) {
          this.elem = elem;
        } else {
          this.elem = new Element();
        }
    }
} 

3 个答案:

答案 0 :(得分:2)

另一种方法是将临时参数存储在共享服务

您必须将服务注入构造函数,以便编写/读取对象参数

答案 1 :(得分:0)

请参阅http://ngcourse.rangle.io/handout/routing/routedata.html有解决方法在javascript中执行此操作

答案 2 :(得分:0)

//Note: router:Router and route:ActivatedRoute
//send object from one component (its independent parent-child relationship with //another component): 
  bill = {
    'customerName': "RAJESH",
    'billNo': "A230",
    'date': "23/12/2020",
    'address': "AGRA",
    'itemDetails':"HUSQVANA VITIPILEN",
    'grandTotal': 2500000
  }
this.router.navigate(['/billingpdf',{billing:JSON.stringify(this.bill)}])

//accessing this object into another component like this:
//-------------------------------------------------------
this.route.snapshot.paramMap.get('billing') //store this variable if you want use further
                                    or
this.route.snapshot.paramMap.getAll('billing')