加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2传递数据以从组件路由

发布时间:2020-12-17 17:42:22 所属栏目:安全 来源:网络整理
导读:我需要将数据从一个组件传递到另一个组件,我发现只有在url中使用路由参数的方法: 所以我对路由器中的目标组件进行了这样的配置: { path: 'edit-tags/:type/:name/:id',component: EditTagsComponent,}, 我使用它来自另一个组件: this.router.navigate([`.
我需要将数据从一个组件传递到另一个组件,我发现只有在url中使用路由参数的方法:

所以我对路由器中的目标组件进行了这样的配置:

{
    path: 'edit-tags/:type/:name/:id',component: EditTagsComponent,},

我使用它来自另一个组件:

this.router.navigate([`../edit-tags/${product.type}/${product.name}/${product.id}`],{ relativeTo: this.route });

它工作正常,但我不想在url中显示id,还需要将更多数据传递给组件.

我也见过在路由器中使用这样的配置:

{ path: 'test-product',component: ProductsContentComponent,data: { role: 'admin',type: 'test-product' } }

但我没有找到在另一个组件中使用相同方法的示例.

那么,有没有办法在路由中将一些数据从组件传递到组件而不在URL中反映它?

解决方法

我们的Web应用程序需要相同的解决方案,我们采用通过服务将数据从一个组件传递到另一个组件的方法.这样,敏感数据不会在URL中表示.这是我们的第一个显示数据列表的组件.我们关注的主要方法是changeRoute方法.在路由更改之前,我们将当前选定的数据保存到dataService,然后执行路由更改.

import { Component,OnInit } from "@angular/core";
import { Router } from "@angular/router";

import { DataService } from "./data.service";
import { Data } from "../../models/data.model";

@Component({
selector: "ei-data-list",template: require("./data-list.component.html")
})
export class DataListComponent implements OnInit {
    constructor(private dataService: DataService,private router: Router) {}

    // .... code for properties and getting data here

    changeRoute(data: Data) {
        this.dataService.data = data;
        this.router.navigate(["/data-list/data-item"]);
    }
}

这是我们构建的数据服务.在这个例子中,我们将它修剪了一下.

import { Injectable } from "@angular/core";
import { Data } from "../../models/data.model";

@Injectable()
export class DataService {
    constructor() { }

    public data: Data;
}

最后,我们有第二个组件,我们传递数据.在ngOnInit中,我们正在收集数据,以便在页面加载时准备就绪.我希望这有帮助.

import { Component } from "@angular/core";
import { DataService } from "./data.service";

@Component({
    selector: "ei-data-item",template: require("./data.component.html")
})
export class DataComponent {
    constructor(private dataService: DataService) {}
    data: Data;

    ngOnInit() {
        this.data = this.dataService.data;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读