Angular2 pass routing data from component

I need to transfer data from one component to another, I found only a way to do this with route parameters in url:

So, I have this configuration for the target component in the router:

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

And I use it like this from another component:

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

It works fine, but I don’t want to show idin the url and also pass some data to the component.

I also saw the use of such configurations in the router:

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

But I did not find an example of using the same approach inside another component.

So, is there a way to pass some data from component to component when routing without reflecting it in the url?

+4
2

-, . , 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;
    }
}
+5

- . , .

- :

export class MyService {
    private searchStringSubject = new Subject<string>();

    searchAnnounced$ = this.searchStringSubject.asObservable();

    announceSearch(searchValue: string) {
        this.searchStringSubject.next(searchValue);
    }
...
}

:

public onSelectSearchValue(e: TypeaheadMatch): void {
    this.chipService.announceSearch(e.item.id);
}

:

ChildComponent OnInit {   : ;   id: string;

constructor(private _service: MyService) {
    this.subscription = _service.searchAnnounced$.subscribe(
        id => {
            this.id = id;
            this.query();
        });

}
0

Source: https://habr.com/ru/post/1664464/


All Articles