【问题标题】:Send JSON from one component to another using routing and not display on URL?使用路由将 JSON 从一个组件发送到另一个组件而不显示在 URL 上?
【发布时间】:2018-06-01 12:28:40
【问题描述】:

我正在尝试在路由 URL 上传递 JSON,这是我的

app.route.ts 代码

 {path: 'calculator', component: CalculatorComponent,data : {some_data : null}},

我的数据路由代码是

 this.router.navigate(['/home/calculator',  {some_data:this.loanData}]);

和calculator.ts有oninit方法代码是这样的

import {ActivatedRoute} from '@angular/router';

    constructor(private route: ActivatedRoute) {}
    sub
    ngOnInit() {
        this.sub = this.route
            .data
            .subscribe(v => console.log(v));
    }

输出是这样的

{"some_data":null}

问题是它没有显示json,我是从ts第一个组件传递过来的

【问题讨论】:

  • 在路由参数中,您应该只传递您希望反映在浏览器 URL 栏中的数据。路由器数据仅用于静态数据。您不能将不同的数据发送到相同的路由,它必须始终相同。为此用例使用共享服务。
  • 你能解释一下或者发给我参考链接吗,因为我不知道
  • 无论如何,在 Angular 5 中,你应该能够... ngOnInit() { this.myVar = this.route.snapshot.data['some_data']; }
  • 如果您想在路由器中获取这些值,请确保使用$router.current.params$routeParams,如AngularjS documentation 中所述
  • 查看plunker

标签: javascript angular


【解决方案1】:
    Is there a reason you want to navigate by url why not use the navigate method like this:

    in RouteConf: { path: '/path/:data', name: 'Defined_Path_Name', component: PathComponent }
    navigate with: this.router.navigate(['Defined_Path_Name', { data: { entity: 'entity' } } ]);

    in /path: console.log(this.routeParams.get('data'))
    that got me: Object {entity: "entity"}

//in your route file 

 in RouteConf: {path: 'calculator/:data', component: CalculatorComponent},

//in your component file navigate by like below

 navigate with: this.router.navigate(['/calculator', { data: this.loaddata } ]);

//and get data in  /calculator path like 

this.data =  this.route.snapshot.data['data'];

than console.log(this.data);

【讨论】:

  • 你能解释一下你的代码以及我必须把这段代码放在哪里
【解决方案2】:

你可以试试这个,这应该可以,希望如此

app.route.ts 代码

{path: 'calculator', component: CalculatorComponent},

和你要路由的代码

 let someData = {
   this.loanData
 };
 this.router.navigate(['/home/calculator/'+someData]);

和calculator.ts有oninit方法代码是这样的

import {ActivatedRoute} from '@angular/router';

    constructor(private route: ActivatedRoute) {}
    sub
    ngOnInit() {
        this.route.params
        .subscribe(data => {
         this.sub = data;
          console.log(this.sub);
});
    }

【讨论】:

  • 错误意味着它只显示 [object,object] 没有我能找到的任何其他值
  • 先检查“this.sub”中的内容,可能你有价值,先检查价值。
猜你喜欢
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 2018-10-18
  • 2016-04-20
相关资源
最近更新 更多