将json从一个组件发送到另一个组件,而不会在目标组件的url中看到

时间:2019-05-27 05:09:48

标签: angular

我正在尝试将json从componentA发送到componentB。问题是json出现在URL中。如何使json不显示?

路由

const appRoutes: Routes = [
  {path: 'componentA', component: componentA},
  {path: 'componentB', component: componentA, data : {}},
  {path: '**', component: NotFoundComponent}
];

模板componentA

<a *ngFor="let item aArray" (click)="fn_sendJson(item)">Send jSON</a>

componentA .ts

this.aArray={"name":"pablo","countrys":["colombia","perú"],"lastname":"ramirez"}
.
.
fn_sendJson(item:any){
 this.router.navigate(['componentB', {"data": JSON.stringify(item)}]);
}

ComponentB .ts

constructor(
 private router : Router,
 private route: ActivatedRoute
 ) {
 sub:any;
 jsonReceived:any
 . 
 .
 this.sub = this.route.params
 .subscribe(v => this.jsonReceived =JSON.parse(v.data));

我还没有找到避免将原始json转换为字符串的方法,我想知道是否存在一种有效的发送方法(例如json),并且无需在URL中显示它就可以获取它。谢谢

2 个答案:

答案 0 :(得分:1)

您可以如下使用 data service

首先,在其中创建一个服务

  share: Subject<any> = new Subject();
  share$: Observable<any> = this.share.asObservable();

然后定义一种方法

shareDate(data:object){
 this.share.next(data);
}

component A

fn_sendJson(item:any){
 this.router.navigate(['componentB']);
 this.serviceName.shareDate({"data": JSON.stringify(item)})
}

,并且在 component B 中,您可以访问以下数据

ngOnInit() {
this.serviceName.share$.subscribe(
  res=>{
        console.log(res)//you will get the data
    }
  }

希望它将解决您的问题!

答案 1 :(得分:1)

当您要将一些复杂的数据从一个组件发送到另一个组件时,通常不建议通过url发送。您可以做的就是创建这样的服务:

sharing.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class SharingService {
  private sharingObject: any;
  constructor() { }

  get sharingValue() {
    return this.sharingObject
  }

  set sharingValue(obj) {
    this.sharingObject = obj;
  }
}

现在,您需要在两个组件中注入该服务,以便在它们之间共享数据。

第一个组件将如下所示:

first.component.ts

import { Component, OnInit } from '@angular/core';
import {SharingService} from '../sharing.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
  myJson: any;
  constructor(private sharingService: SharingService, private router: Router) {
    this.myJson = {
      a: "hello",
      b: "World"
    }
  }

  ngOnInit() {
  }

  send() {
    this.sharingService.sharingValue = this.myJson;
    this.router.navigate(['/second'])
  }

}

现在在第二个组件中,您可以访问第一个组件设置的值

second.component.ts

import { Component, OnInit } from '@angular/core';
import {SharingService} from '../sharing.service';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {
  myJson: any;
  constructor(private sharingService: SharingService) { }

  ngOnInit() {
   this.myJson = this.sharingService.sharingValue;
  }

}

这是此方法的有效堆栈demo

希望它会有所帮助:)