我正在尝试将 json 从 componentA 发送到 componentB。问题是 json 出现在 url 中。我怎样才能让json不出现?
路由
const appRoutes: Routes = [
{path: 'componentA', component: componentA},
{path: 'componentB', component: componentA, data : {}},
{path: '**', component: NotFoundComponent}
];
模板组件A
<a *ngFor="let item aArray" (click)="fn_sendJson(item)">Send jSON</a>
组件 .ts
this.aArray={"name":"pablo","countrys":["colombia","perú"],"lastname":"ramirez"}
.
.
fn_sendJson(item:any){
this.router.navigate(['componentB', {"data": JSON.stringify(item)}]);
}
组件 .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中就可以获取它。谢谢
当您想将一些复杂的数据从一个组件发送到另一个组件时,通过 url 发送它通常不是一个好习惯。您可以做的是创建这样的服务:
共享服务.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'])
}
}
现在在您的第二个组件中,您可以访问由第一个组件设置的值
第二个组件.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;
}
}
这是这种方法的工作 stacklitz演示
希望能帮助到你 :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句